Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP lose item value of array?

Tags:

arrays

php

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?

like image 295
Weltkind Avatar asked Feb 13 '17 12:02

Weltkind


4 Answers

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');
like image 96
Mohammad Avatar answered Nov 06 '22 12:11

Mohammad


When $array is being created, 'Boss' will first be stored in index 2 (Array([2] =>'Boss') which is later overwritten by 'Lynx'

like image 40
Karthick Vinod Avatar answered Nov 06 '22 14:11

Karthick Vinod


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.

like image 3
Rahul Avatar answered Nov 06 '22 13:11

Rahul


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.

like image 3
Tomáš Tatarko Avatar answered Nov 06 '22 14:11

Tomáš Tatarko