PHP Foreach Arrays and objects PHP Foreach Arrays and objects arrays arrays

PHP Foreach Arrays and objects


Use

//$arr should be array as you mentioned as belowforeach($arr as $key=>$value){  echo $value->sm_id;}

OR

//$arr should be array as you mentioned as belowforeach($arr as $value){  echo $value->sm_id;}


Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

foreach ($arr as $item) {    echo $item->sm_id;}

In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

foreach ($arr as $index => $item) {    echo "Item at index {$index} has sm_id value {$item->sm_id}";}


Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray){    foreach ($objOrArray as $key => &$value)    {        if (is_array($value) || is_object($value))        {            traverse($value);        }        else        {            // DO SOMETHING        }    }}