Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function to extract a 'column' from an array in PHP?

Tags:

arrays

php

I have an array of arrays, with the following structure :

array(array('page' => 'page1', 'name' => 'pagename1')
      array('page' => 'page2', 'name' => 'pagename2')
      array('page' => 'page3', 'name' => 'pagename3'))

Is there a built-in function that will return a new array with just the values of the 'name' keys? so I'd get:

array('pagename1', 'pagename2', 'pagename3')
like image 374
Skilldrick Avatar asked Sep 29 '09 21:09

Skilldrick


2 Answers

As of PHP 5.5 you can use array_column():

<?php $samples=array(             array('page' => 'page1', 'name' => 'pagename1'),             array('page' => 'page2', 'name' => 'pagename2'),             array('page' => 'page3', 'name' => 'pagename3')             ); $names = array_column($samples, 'name'); print_r($names); 

See it in action

like image 156
John Conde Avatar answered Sep 19 '22 18:09

John Conde


Why does it have to be a built in function? No, there is none, write your own.

Here is a nice and easy one, as opposed to others in this thread.

$namearray = array();

foreach ($array as $item) {
    $namearray[] = $item['name'];
}

In some cases where the keys aren't named you could instead do something like this

$namearray = array();

foreach ($array as $key => $value) {
    $namearray [] = $value;
}
like image 27
Anti Veeranna Avatar answered Sep 18 '22 18:09

Anti Veeranna