Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Foreach Arrays and objects

I have an array of objects; running print_r() returns the output below;

Array (     [0] => stdClass Object         (             [sm_id] => 1             [c_id] => 1         )     [1] => stdClass Object         (             [sm_id] => 1             [c_id] => 2         ) ) 

How to loop through the result and access the student class objects?

like image 954
AttikAttak Avatar asked Dec 04 '12 16:12

AttikAttak


People also ask

Can I use foreach on object in PHP?

PHP provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement.

How do you iterate through an array of objects in PHP?

Use the foreach($array_name as $element) to iterate over elements of an indexed array. Use the foreach($array_name as $key => $value) to iterate over elements of an associative array.

Does foreach work on objects?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object.

What is foreach of array in PHP?

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype. The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.


2 Answers

Use

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

OR

//$arr should be array as you mentioned as below foreach($arr as $value){   echo $value->sm_id; } 
like image 144
GBD Avatar answered Sep 24 '22 13:09

GBD


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}"; } 
like image 35
Sampson Avatar answered Sep 26 '22 13:09

Sampson