PUG
PUG

Reputation: 351

PHP:: cannot retrieve all values inside array

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 ?!

Upvotes: 0

Views: 53

Answers (4)

Karnail Singh
Karnail Singh

Reputation: 116

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

?>

Upvotes: 1

Ju Oliveira
Ju Oliveira

Reputation: 428

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'

Upvotes: 2

Indrasis Datta
Indrasis Datta

Reputation: 8618

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

Upvotes: 2

Rahul
Rahul

Reputation: 18557

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.

Upvotes: 3

Related Questions