Is there a function to extract a 'column' from an array in 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')
Solution 1:
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
Solution 2:
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;
}