Let's say I have two arrays:
$array1 = ['A', 'B', 'C', 'D'];
$array2 = [
['name' => 'B', 'number' => 10],
['name' => 'D', 'number' => 20]
];
I want to compare $array1
with $array2
's name
column. If a value of $array1
mathches with $array2'
s name
column then corresponding number
column value will be printed otherwise left empty.
Desired output:
$array3 = ['','10','','20'];
I've tried like this:
$array3 = [];
foreach ($array1 as $key => $value) {
$array3[$key] = (in_array($value, array_column($array2 , 'name'))) ? array2[$key]['number'] : '';
}
It is not working as I'm expecting. How can I achieve this?
How is array2[$key]['number']
supposed to make sense, considering that your $key
goes from 0 to 3, but array2 only has elements under key 0 and 1?
Also, missing the $ sign before the variable name there - go and enable proper PHP error reporting, so that PHP can tell you about mistakes like this!
Use array_search
instead of in_array
, so you get the key of the element found in $array2.
foreach($array1 as $key=>$value){
$array2key = array_search($value,array_column($array2 , 'name'));
$array3[] = $array2key !== false ? $array2[$array2key]['number'] : '';
}