2

I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :

for instance:

array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)

into:

array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)
3
  • 6
    array keys must be unique, please change the second code line Commented Jul 12, 2012 at 6:10
  • so.. there is no way to get an array into that format? Perhaps i used the wrong terminology? I thought i meant key-value pair.. but what i really am looking for is an array in the format of that in the second code line Commented Jul 12, 2012 at 6:13
  • "same key"? Is there any requirement to do so? It's not a feasible concept. Commented Jul 12, 2012 at 6:16

3 Answers 3

5

You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:

array(
    [animals] => array(
        [0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
    )
) 

this can be used with $array['animals'][0]

But still you need numbers or unique identifiers to access the values of the array.

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

Comments

3

Something like this:

$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);

$arrayReturn['animals'] = $array;

print_r($arrayReturn);

1 Comment

quote from OP. first sentence: "I have a comma separated string which i explode into an array."
0

u cant have same key for all the values but u can do this

lets say your string is

$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
   $yourArray['animals']=$animals;
}

Now it doesnot matter how long your string is you will have you array as

$yourArray['animals'][0]='dog'

$yourArray['animals'][1]='ant'

....... so on ......

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.