Reputation:
$fruit = array(0 => "Lemon", 1 => "Apple");
$order = array(0 => "no1", 1 => "no2");
$new_array = array();
foreach ($order as $index) {
$new_array[$index] = $fruit[$index];
}
print_r($new_array);
It shows:
Notice: Undefined index: no1 in C:\xampp\htdocs\jobs.php on line 6
Notice: Undefined index: no2 in C:\xampp\htdocs\jobs.php on line 6
What should I do? Thank you :)
Upvotes: 0
Views: 85
Reputation: 1901
You should use array_combine()
function available in PHP (see PHP Docs) :
"array_combine — Creates an array by using one array for keys and another for its values"
$fruit = array(0 => "Lemon", 1 => "Apple");
$order = array(0 => "no1", 1 => "no2");
$new_array = array_combine($order, $fruit);
print_r($new_array);
// Output : Array ( [no1] => Lemon [no2] => Apple )
Working example: https://3v4l.org/rW71r
Upvotes: 2
Reputation: 128
To achieve that you need to use the key of the loop and use that to get the fruit, just keep in mind that you will get a notice if the key doesn't exist as you did above.
$fruit = array(0 => "Lemon", 1 => "Apple");
$order = array(0 => "no1", 1 => "no2");
$new_array = array();
foreach ($order as $key => $index) {
$new_array[$index] = $fruit[$key];
}
print_r($new_array);
Upvotes: 0