How exactly can I apply array_column()
to always get the first column of an array instead of getting the column by name?
I am seeking something like this is:
array_column($array,[0])
instead of:
array_column($array,"key");
How exactly can I apply array_column()
to always get the first column of an array instead of getting the column by name?
I am seeking something like this is:
array_column($array,[0])
instead of:
array_column($array,"key");
Try
array_column($array, array_shift(array_keys($array)));
from Return first key of associative array in PHP
Hope can help! :)
You can't do this with the array_column
function, unless you know for certain what the key is for first element of each array is going to be ahead of time.
You'll need to do this with a foreach()
and use reset()
to get the first elements.
While array_column()
will allow you to target a column using an integer, it needs to be an existing integer key. Otherwise, you will need to determine the first subarray's first key to gain access to that column dynamically.
Code: (Demo)
$array = [
["foo" => "bar1", "hey" => "now"],
["foo" => "bar2", "hey" => "what"],
[0 => "zero", 1 => "one"]
];
var_export(array_column($array, 'foo')); // get the column by name
echo "\n---\n";
var_export(array_column($array, 0)); // don't need to be a string
echo "\n---\n";
var_export(array_column($array, key(current($array)))); // access the first subarray, access its key
echo "\n---\n";
var_export(array_column($array, array_shift(array_keys($array)))); // this generates a Notice, and damages the array
Output:
array (
0 => 'bar1',
1 => 'bar2',
)
---
array (
0 => 'zero',
)
---
array (
0 => 'bar1',
1 => 'bar2',
)
---
Notice: Only variables should be passed by reference in /in/hH79U on line 14
array (
0 => 'zero',
)
If you use a loop or functional iterator, you can call current()
or reset()
to access the first element of each row, but if those first elements have different keys, then this is not technically a column of data. See what I mean in the demo -- you inadvertently grab values from different keys.
var_export(array_map('current', $array));
// ['bar1', 'bar2', 'zero']