-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

Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
Geek
  • 29
  • 1
  • 3
  • I am still not getting any solution for this on that link. Can you please help me out? – Geek Apr 23 '16 at 15:13

2 Answers2

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

Community
  • 1
  • 1
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
  • @LightnessRacesinOrbit Maybe i didn't understood the question correctly. Doesn't the OP requested to convert the array keys to strings? – Alon Eitan Apr 23 '16 at 15:33
  • 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] – Geek Apr 23 '16 at 15:38
  • @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. – Alon Eitan Apr 23 '16 at 15:52
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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055