I have the array with values:
$array1 = array('Boss', 'Lentin', 'Endless');
print_r ($array);
The result will be:
Array ( [0] => Boss [1] => Lentin [2] => Endless
It's ok.
But, if I add two elements to this array with a keys, the "Boss" element will be lost.
$array2 = array("1"=>'Doctor','Boss', 2=>'Lynx', 'Lentin', 'Endless');
print_r ($array2);
The result will be:
Array ( [1] => Doctor [2] => Lynx [3] => Lentin [4] => Endless )
//Where is "BOSS"???
Why?
When php create the array, set Doctor
in index 1 and Boss
in index 2, but 2=>'Lynx'
cause php overwrite index 2 and set Lynx
in it.
You can set it after setted index or use index for it. For example like
$array2 = array("1"=>'Doctor', 2=>'Lynx', 'Boss', 'Lentin', 'Endless');
// or
$array2 = array("1"=>'Doctor', 2=>'Boss', 3=>'Lynx', 'Lentin', 'Endless');
When $array is being created, 'Boss' will first be stored in index 2 (Array([2] =>'Boss')
which is later overwritten by 'Lynx'
Your issue is index keys
$array2 = array("1"=>'Doctor','Boss', 2=>'Lynx', 'Lentin', 'Endless');
print_r ($array2);
This is because, on index 1 it is already doctor, boss will be second, which will be replaced by Lynx which have same index of 2 where boss will be replaced.
I hope I am clear.
This is expected behaviour from php (see http://php.net/manual/en/language.types.array.php#example-57). In case you need all the values in the array and don't need to work with keys, I recommend to use array_push($array $value)
. Otherwise you should add all the values with their keys and remember that for PHP 1
and "1"
and true
are the same values so they will overwrite each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With