0

I have an array with 2 same keys i want to foreach out if possible. The currently code looks like:

$arrayName = array(
    1 => array('detail' => 'detail1' , 'detail' => 'detail2')
);

foreach ($arrayName[1] as $key['detail'] => $value) {
     echo $value;
}

Thanks for any help!

2 Answers 2

5

Your keys are overwriting themselves. You may want to approach the solution like this:

$arrayName = array(
    array('name' => 'detail' , 'value' => 'detail1'),
    array('name' => 'detail' , 'value' => 'detail2')
);

foreach ($arrayName as $i) {
    echo $i['value'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped me out to understand how to do it. Cheers!
2

You cannot have identical keys for an array.. The final key overwrites the first one. (in your case)

From the PHP Docs..

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

A dynamic way of doing this..

<?php
$new_arr = array();
foreach(range(1,5) as $v)
{
    $new_arr['detail'.$v]='detail'.$v;
}
print_r($new_arr);

OUTPUT :

Array
(
    [detail1] => detail1
    [detail2] => detail2
    [detail3] => detail3
    [detail4] => detail4
    [detail5] => detail5
)

3 Comments

Why not different keys ? :) detail1 and detail2 ?
I building an application and want to keep it easy :)
Then create an array of arrays and keep the key same for the sub arrays

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.