A.C.Balaji
A.C.Balaji

Reputation: 1113

PHP : best way to get all the elements of an object?

what is the best way to access all the elements of the object instead of using foreach?

Thanks in advance...

Upvotes: 1

Views: 2210

Answers (2)

The Surrican
The Surrican

Reputation: 29874

What's wrong with foreach?

Well but there are several methods

You could do something like:

$length = count($arr);
for($i = 0; $i<$length; $i++)

you could also do

while($i < $length)

and access the items directly if you do have numeric keys.

However foreach won't be slower and its the best way to go if you don't have numeric keys.

You can also access the items using next($arr) or you can push/pop

I would say it depends on the context what you want to do.

If you want to do X operations with an array of size X for example you need some loop.

If yuo only want to apply the very same operation on all elements you can use the handy function array_map

if you just want to get all information from it you could also use get_object_vars however, then you have just a new array and what then?

It really depends on the context what you want to do!

In most cases foreach is fine and fast.

If you want to search for specific keys/values or see whether they exists, there are special optimized array functions for that,.

Upvotes: 1

ajreal
ajreal

Reputation: 47321

get_object_vars — Gets the properties of the given object

details - http://php.net/manual/en/function.get-object-vars.php

Upvotes: 4

Related Questions