Looping an array? Do it the foreach way
Last Updated on: February 11, 2023
As an example, if you have an array of users with an ID field as the key and the username as the value, such as:
$arr = array ( 566 => 'monkeybrains', 891 => 'bananaface, 4459 => 'treehugger' );
You may want to perform an action on or with each of these array elements. If the array is assigned to the value $users you can loop through easily and logically as follows:
foreach ($users as $user_id => $user_name) { echo "$user_name has user_id $user_id"; }
Doing it this way makes the most sense to me and flows better in the code. In some examples, I have seen programmers use the key of each array sequentially, so as to be able to loop the array in a for loop, such as:
for ($i=0; $i < sizeof($users); $i++) { echo $users[$i]." has user_id $i"; }
For me, this is cumbersome and does not read very well. It relies on your keys being ordered 0,1,2,3 … etc. and to format them this way would take more logic and checks.
Get notified of new posts: