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')
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With