0

I have the following array:

 Array (
                [0] => Array 
                (
                    [example] => 'h'
                )
                [1] => Array 
                (
                    [example] => 'e'
                ) 
                [2] => Array 
                (
                    [example] => 'l'
                )
                [3] => Array 
                (
                    [example] => 'p'
                )
        )

And I am wondering how can I change this array to look like this instead.

Array( [example] => 'h', [example] => 'e', [example] => 'l', [example] => 'p')

I have tried using a nested foreach loop but using that I only get the values and not as an array.

4
  • 3
    You can't change it to look the way you want, because that entails duplicate keys (example) Commented Jan 6, 2014 at 19:28
  • What do you want to have as keys? minimal reproducible example is obviously duplicated in your expected result and thus cannot be used as a key. Are the inner arrays num-indexed or do you need to preserve their keys as well? (@MarkBaker is comment-ninja) Commented Jan 6, 2014 at 19:28
  • Well the thing is I do want to preserve their keys because I want to use it in an SQL statement, are you saying there is no way to convert it to how I would like it? Commented Jan 6, 2014 at 19:33
  • Not to how you like it, but something like Array ( [example] => Array( [0] => 'h', [1] => 'e', [2] => 'l', [3] => 'p') ) can be done. Commented Jan 6, 2014 at 19:34

1 Answer 1

2

There are a couple of ways to reach the values of a multidimensional array:

$array = array(
    0=>array('example'=>'h'),
    1=>array('example'=>'e'),
    2=>array('example'=>'l'),
    3=>array('example'=>'p')
);

1, If looping through the array:

foreach($array as $key=>$value){
    echo $value['example'];
}

2, Call a value directly:

echo $array[0]['example'];
echo $array[1]['example'];
echo $array[2]['example'];
echo $array[3]['example'];

It is impossible to create an array the way that you mentioned (having 4 'example' as keys). Take the following for example:

$array['example'] = 'h';
$array['example'] = 'e';
$array['example'] = 'l';
$array['example'] = 'p';
echo $array['example'];

The output would be p because you are simply overwriting the variable $array['example'] each time.

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

1 Comment

Oh ok then, thank you I will have to rethink my code to get it the way I want it.

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.