foreach – PHP ArrayObject / ArrayIterator : concept with example-ThrowExceptions

Exception or error:

I’m trying to understand the concept of the Object Array in PHP.
Up to date I was simply using regular arrays to loop through the list of records and display them in say table.

I know that I could do this using Object, but I’m not quite sure how to do it.

I understand the concept of a single Object instance with all properties representing the fields with their associated values populated from the database, which can be called like:

$objUser->first_name;

Now what I would like to understand, and simply cannot find a simple answer to is how to deal with let’s say list of users, which I would like to display on one page. I’ve seen that there are ArrayObject, ArrayIterator etc., but simply cannot understand how they work so if someone could try to explain it with a few examples of how the above can be accomplished that would be much appreciated.

What I’m looking for is an object containing the list of elements, which I can loop through like so (if at all this is possible):

foreach($objUsers as $objUser) {
    echo $objUser->first_name;
}

Thanks.

How to solve:

It is possible. Have your object implement the Iterator interface, and then you will be able to foreach over it natively. (Note, you need to correctly implement the methods to advance and rewind your array)

More info:

Answer´╝Ü

If I reach the problem, you asking how to work with many objects?

So, if you use the array of object, for example, from ORM.

$users_list = new Users();
$arr_users = $users_list->all();

In $arr_users you will have an array with many users objects from your DB.
Every object have some properties, for example – id, name, gender and age.

foreach($arr_users as $single_user) {
    echo $single_user->id;
    echo $single_user->name;
    echo $single_user->gender;
    echo $single_user->age;
}

If you need just one user:

echo $arr_users[1]->name;

Also you can work with array of objects like this.
Firstly, made new array from $arr_users;

foreach($arr_users as $single_user){
$arr_user_by_id[$single_user->id] = $single_user;
}

Now you have new array, where keys are user id, and value – object user.

So you can get user info by his ID.

echo $arr_users[$_GET['uid']]->name;

I hope I could help a little bit to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *