Paul Paul - 1 month ago 7
PHP Question

Adding 0 (Zero) as Key in array doesn't work but when i change it to 1 it works

I'm still confused why when i use 0 as key in array it does not work but when i changed it to 1 it works normally. Can someone explain me why this is happening.
Thanks in advance.

$myArray = {1,2,3,4}



Using foreach loop to get the data and to add to my new array



$o = array();
foreach($myArray as $key=>$value){
//using to $key to set the key for item in my array
$o[$key] = $value;
}


Output should be like this



$o={0:1,1:2,2:3,3:4}



But when the key start with 0 it returns like this

$o={1,2,3,4}



When i change it to

$o = array();
foreach($myArray as $key=>$value){
//using to $key to set the key for item in my array
$o[$key+1] = $value;
}


the ouput



$o={1:1,2:2,3:3,4:4}



my main goal ouput



$o={0:1,1:2,2:3,3:4}


Answer

check this,

<?php

$o = array(1,2,3,4);

$bind = array();
foreach($o as $key=>$value){
    $bind[] = $key.":".$value;
}

echo implode( ',', $bind );

?>


Output: 0:1,1:2,2:3,3:4
Comments