0
$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 :)

Arslanbekov Denis
  • 1,674
  • 12
  • 26
  • 1
    Please include what your desired output would be – Joseph Cho Oct 18 '18 at 18:06
  • I would like to make this Array ( [no1] => Lemon [no2] => Apple) –  Oct 18 '18 at 18:10
  • Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – olibiaz Oct 18 '18 at 18:44

2 Answers2

2

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

André DS
  • 1,823
  • 1
  • 14
  • 24
0

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);
shauns2007
  • 128
  • 9