I often encounter a situation where I have to get an array of values that come from multiple objects. Let me clarify that with an fictional situation and some code.
Imagine I have created a class…
class MyObject {
public $x = 0;
public $y = 0;
}
I have an array of instances…
$instances = array(
new Object,
new Object,
new Object
);
and I want to join all x properties as strings, devided with comma’s… I would have to use a loop…
$array = array();
foreach($instances as $instance) array_push($array, $instance->x);
$str = implode(',', $array); // holds an array of all x values
That would totally work, but I am very much against unnecessary loops and pro native implementations because I have a little obsession for performance – I dislike looping through huge arrays only to get a single property off every instance.
Is there a native way to get an array of property values from multiple objects? If so, how? If not, any idea why not?
Thanks in advance.
A simple easy way is to use
array_mapOr
array_reduceThe both would output
You can also modify your class to use
__toString()ExampleOutput