0

Here is my simple code:

<?php

$components=array(
1 => 'Carrot', 'Apple', 'Orange',
2 => 'Boiled Egg', 'Omelet',
3 => 'Ice Cream', 'Pancake', 'Watermelon'
);

echo'<pre>';
var_dump($components);
echo'</pre>';

output :

array(6) {
  [1]=>
  string(6) "Carrot"
  [2]=>
  string(10) "Boiled Egg"
  [3]=>
  string(9) "Ice Cream"
  [4]=>
  string(6) "Omelet"
  [5]=>
  string(7) "Pancake"
  [6]=>
  string(10) "Watermelon"
}
  1. Where is 'Apple' & 'Orange' ?
  2. Why I cannot retrieve the a specific value from (for example : $components[1][2] = 'r') :/ Why ?!
Cœur
  • 37,241
  • 25
  • 195
  • 267
PUG
  • 331
  • 1
  • 4
  • 14
  • what a fuss mate, is your array correct, once correct your array, it will work. – Rahul Mar 22 '17 at 10:54
  • 1
    The answers to both questions can be found in the [documentation](http://php.net/manual/en/language.types.array.php#example-60). – axiac Mar 22 '17 at 11:11

4 Answers4

3

Make an array like this,

$components=array(
  1 => ['Carrot', 'Apple', 'Orange'],
  2 => ['Boiled Egg', 'Omelet'],
  3 => ['Ice Cream', 'Pancake', 'Watermelon']
);

And now check your array.

Rahul
  • 18,271
  • 7
  • 41
  • 60
2

From your given syntax, it's forming a single dimensional array, not a multi-dimensional array.

Try this:

$components=array(
    1 => array('Carrot', 'Apple', 'Orange'),
    2 => array('Boiled Egg', 'Omelet'),
    3 => array('Ice Cream', 'Pancake', 'Watermelon')
 );
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
2

You need to organize your array like this:

$components = array(
   1 => array(
         1 => 'Carrot',
         2 => 'Apple',
         3 => 'Orange'
   ),
   2 => array(
         1 => 'Boiled Egg',
         2 => 'Omelet'
   ),
   3 => array(
         1 => 'Ice Cream',
         2 => 'Pancake',
         3 => 'Watermelon'
   ),
);

Then you'll be able to obtain: $components[1][2] = 'Apple'

Ju Oliveira
  • 428
  • 8
  • 14
1

You may use string into array index Like this

 <?php
$components=array(
1 => ['Carrot', 'Apple', 'Orange'],
2 => ['Boiled Egg', 'Omelet'],
3 => ['Ice Cream', 'Pancake', 'Watermelon']
);

echo "<pre>";
print_R($components);

?>

Karnail Singh
  • 116
  • 1
  • 12