1

Say I have an array of Person objects and the person objects have properties firstName, lastName, and age. Now suppose I want an array of the firstnames of all these person objects. How can I convert this array of Person objects into an array of firstname strings?

Is there some combination of array functions I can use to do it or do I just have use a for loop and create a new array?

4 Answers 4

4

You can use array_map

    class Person
{
    public $firstName ;
    public $lastName ;
    public $age ;

    function __construct($firstName,$lastName,$age)
    {
        $this->firstName = $firstName ;
        $this->lastName = $lastName ;
        $this->age = $age ;
    }
}

$list = array();
$list[] = new Person("John", "Smith", 22);
$list[] = new Person("Jon", "Doe", 19);
$list[] = new Person("Jane", "Stack", 21);

$lastNames = array_map(function($var){return $var->lastName ; } ,$list);
var_dump($lastNames);

Output

array
  0 => string 'Smith' (length=5)
  1 => string 'Doe' (length=3)
  2 => string 'Stack' (length=5)
Sign up to request clarification or add additional context in comments.

1 Comment

Newer versions of PHP can use this format: array_map(fn($var) => $var->lastName, $list);
0

You can loop through the array of person objects, and then loop through the person object and create array from the firstname property. See an example, which coincidently uses a person class as an example:

http://www.tuxradar.com/practicalphp/6/7/6

Comments

0

A simple loop would be the best:

$persons = getPersons();

$firstnames = array();

foreach($persons as $person) {
    $firstnames[] = $person->getFirstName();    
}

Comments

0

You have to loop through the array of objects. Either use the normal foreach or use array_map.

function get_first_name($person)
{
    return $person->firstName;
}
$firstNames = array_map('get_first_name', $people);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.