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 ?!
2
  • what a fuss mate, is your array correct, once correct your array, it will work. Commented Mar 22, 2017 at 10:54
  • 1
    The answers to both questions can be found in the documentation. Commented Mar 22, 2017 at 11:11

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Working :) Thank you!
Happy to help, and welcome. If this answer or any other one solved your issue, please mark it as accepted.
Need to wait 7 minutes to accept it (policy)... hmmm :/ ok... I'll wait
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')
 );

Comments

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'

Comments

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);

?>

4 Comments

OP does NOT have any strings in there. Those are array elements of string type
Yes @bub but i just answer your question Where is 'Apple' & 'Orange' ?
This is the way how you get all data according to your question .
I didn't have any question :) I just mentoined that your post does not provide an answer to OPs question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.