It is known that array_combine
is used only for two arrays. For example
$name = array('John','Brian','Raj');
$salary = array('500','1000','2000');
$details = array_combine($name, $salary);
foreach($details AS $name => $salary){
echo $name."'s salary is ".$salary."<br/>";
}
Let add 2 arrays in this list
$dpart = array('HTML','CSS','PHP');
$address = array('Floor 3','Floor 5','Floor 6');
In that case, only array_combine()
is not enough, so I found array_map()
is the better solution here. But how to echo array_map()
result? How to access values of array generated by array_map()
and fetch according individual requirement.
$details = array_map(function($item) {
return array_combine(['name', 'salary', 'dpart', 'address'], $item);
}, array_map(null, $name, $salary, $dpart, $address));
Now requirement is to access all four arrays with individual values. For example
$name."'s salary is ".$salary.", address is ".$address.", depart is ".$dpart
You can access result simply using foreach
. Loop $details
as
foreach($details as $item) {
$name = $item['name'];
$salary = $item['salary'];
$dpart = $item['dpart'];
$address = $item['address'];
echo $name."'s salary is ".$salary.", address is ".$address.", depart is ".$dpart."<br/>";
}
Or without the assignment within the loop:
foreach($details as $item)
print "{$item['name']}'s salary is {$item['name']}, address is {$item['dpart']}, depart is {$item['address']}<br/>";