-4

I am stuck somewhere in arrays. I am getting an array like:

Array
(
    [0] => name
    [1] => description
)

And I want to convert that into :

Array
(
    "0" => name
    "1" => description
)

I have found on google enough for this but did not found any solution, and don't think it is object array.

Can someone please help me out in this.

Thanks

1
  • I am still not getting any solution for this on that link. Can you please help me out? Commented Apr 23, 2016 at 15:13

2 Answers 2

0

Based on the duplicated answer, this is how you should do it

$data = array(0 =>'name', 1=> 'description');

$keys = array_keys($data);
$values = array_values($data);

$stringKeys = array_map('strval', $keys);
$data = array_combine($stringKeys, $values);
var_dump($data);

Output

array(2) { 
    [0]=> string(4) "name" 
    [1]=> string(11) "description" 
}

There is a small syntax error there- array_map($keys, 'strval') should be array_map('strval', $keys)

BTW, I don't understand why you need this:

$data = array("name", "description");

echo $data[0]; // output: "name"
echo $data["0"]; // Also output: "name"

So in both cases you get the same output

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

3 Comments

@LightnessRacesinOrbit Maybe i didn't understood the question correctly. Doesn't the OP requested to convert the array keys to strings?
I want to convert [0] to "0" because, I have 2 arrays and I further want there difference by array_diff. and array_diff does not accept array index as [0]
@addy I suggest you should update the question white this important information, and explain why do you think it's not a duplicate. You should also include the code that doesn't work because people like to see what have you tried before asking the question (You can combine it with the code from my answer) - This will reopen your question and allow us to help you.
0

You're misreading the output. The keys are not [0] and [1]; they are the integers 0 and 1, stylised for debug output.

You can have string keys instead if you like (i.e. ["0"] and ["1"] in the output), but since PHP will coerce between the two as needed anyway, there's really no point.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.