0
$icecream = array (
    "Choco" => array('2 Dollars'),
    "Mango" => array('3 Dollars')
 );

print $icecream[0][0];

expected output: 2 Dollars

Edit: I have a huge list of icecream sorts and i do want to use a loop to output all the information as a HTML DOM. So I do not want to go through each array value and echo it with the explicit value (i.e. 'Choco', 'Orange', etc...).

I want to use values as keys for the "first array level" ($icecream[0]),

It does output nothing at all. What is my logical flaw with this solution?

1
  • 2
    you have to print $icecream["Choco"][0] (you have key name so you can't access it with position number 0) Commented Apr 16, 2013 at 7:49

3 Answers 3

6

try this:

echo $icecream['Choco'][0]

Your problem here is calling the wrong key for the 1st dim

. .

For your updated question, try this:

$ice_k = array_keys($icecream);
echo  $icecream[$ice_k[0]][0];
Sign up to request clarification or add additional context in comments.

2 Comments

I edited the question to provide the necessary context. I'm sorry for inconvenience.
@RaheelHasan +1 for sportsmanship, helping two times so user satisfy.
0

You're not using the associative array right. You need to use the right key.

    echo $icecream['choco'][0];

2 Comments

But what if the first item of the array will change it's name? I can't rely on the explicit value. Can't I use the position of the first array item?
But how do you which position is what flavour? The most logic thing would be to give them an id that never changes and a name that could change.
0

You can use position but it will be a counter like this:

$counter = 0;
foreach($icecream As $k=>$v) {
    echo $icecream[$k][0] . ' [' . $counter . ']';
    $counter++;
}

and if you want to get only value you can use previous code

$ice_k = array_keys($icecream);
$position = 5;
if( isset($ice_k[$position]) ) {
    echo  $icecream[$ice_k[$position]][0];
}

Comments

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.