The array looks like
$arr = array(
array('a', 'b'),
array('c', 'd'),
array('e', 'f'),
)
And I want to get an array with values from the first column, like array('a', 'c', 'e')
I know it can easily be done by iterating the array and store the values in another array, but is there a shorter way, a built-in PHP function or something?
Using array_slice() function: array_slice() returns the sequence of elements from the array as specified by the offset and length parameters. Example: This example illustrates the array_slice() Function to fetch a part of an array by slicing through it, according to the user's choice.
To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.
Flattening a two-dimensional arrayarray_merge(... $twoDimensionalArray); array_merge takes a variable list of arrays as arguments and merges them all into one array. By using the splat operator ( ... ), every element of the two-dimensional array gets passed as an argument to array_merge .
As of PHP 5.5 you can use array_column()
:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith'
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones'
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe'
)
);
$lastNames = array_column($records, 'last_name', 'id');
print_r($lastNames);
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)
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