Search code examples
phparraysoopforeacharray-map

Getting object member variable in one line of code from an array of objects in php


I am caught in a situation where I need to get values of a member variable of instances of an object which are in an array. Is there any way to use a function like array_map to get them in one line rather than using a foreach loop. Please see the code example below.

<?php

Class abc
{
   public $aVar;
   function __construct($Initialize)
   {
       $this->aVar = $Initialize;
   }
};

$Array = array(new abc(10), new abc(20), new abc(30));

$Array2 = array();

foreach ($Array as $Element)
{
    array_push($Array2, $Element->aVar);
}

print_r($Array2);
?>

Output is:

Array (

[0] => 10

[1] => 20

[2] => 30

)


Solution

  • You could use:

    $newAray = array_map(function ($abcObj) {
        return $abcObj->aVar;
    }, $Array);
    
    print_r($newAray);
    

    Output:

    Array
    (
        [0] => 10
        [1] => 20
        [2] => 30
    )
    

    Though, performance-wise, I'd guess this doesn't change much.

    Edit: Actually using array_map is far worse than foreach. Just a quick test with microtime and 1000000 iterations gave me:

    foreach: 0.83289s
    array_map: 2.95562s
    

    on my test machine. So, I'd say, stick with the foreach.