0

Sorry to ask, it's only for my understanding !

I just start learning php.

I added some values from different method to an array and
it come to a strange problem that i can't find an answer on the web.
(sorry if it's stupid, i just want to know why it do that.)

My PHP/HTML code:

<?php 
$test[] = 1;
$test += array('2','3','4');
$test += array('4in4',5 => '5');
$test[] = 6;
$test[] += 7;
?>
<!doctype html>
<html lang="fr-CA" >
<head>
<meta charset="UTF-8">
<body>
<?php echo '<h1>Test de Tableau</h1>','<br>',
    '$test[0] = ',$test[0],'<br>',
    '$test[1] = ',$test[1],'<br>',
    '$test[2] = ',$test[2],'<br>',
    '$test[3] = ',$test[3],'<br>',
    '$test[4] = ',$test[4],'<br>',
    '$test[5] = ',$test[5],'<br>',
    '$test[6] = ',$test[6],'<br>',
    '$test[7] = ',$test[7],'<br>',
    '<h4>count = ',count($test),'/8</h4>'; ?>
</body>


And here is the result :


Test de Tableau

$test[0] = 1
$test[1] = 3
$test[2] = 4
$test[3] =
Notice: Undefined offset: 3 in /opt/lampp/htdocs/mhx/test/index.php on line 26
$test[4] =
Notice: Undefined offset: 4 in /opt/lampp/htdocs/mhx/test/index.php on line 27
$test[5] = 5
$test[6] = 6
$test[7] = 7
count = 6/8

Thanks to answer !
MHX

MHX
  • 21
  • 3

1 Answers1

2

This may have already been answered by this post: + operator for array in PHP?

Essentially, here's what's happening. You initialized your array:

$test = [0 => 1];

Next, you're adding a new array to it:

[0 => '2', 1 => '3', 2 => '4'];

The first index already exists, so it's skipped giving us:

$test = [0 => 1, 1 => '3', 2 => '4'];

Now, you're adding another array:

[0 => '4in4', 5 => '5'];

Again, the first index exists, so we get:

$test = [0 => 1, 1 => '3', 2 => '4', 5 => '5'];

By now, you can see that offsets 3 and 4 are missing, hence your notices above. Also, the internal pointer is now at 6 since the last element added was at 5.

You then add 6, followed by 7, giving us the final array:

$test = [0 => 1, 1 => '3', 2 => '4', 5 => '5', 6 => 6, 7 => 7];

I hope this helps.

EDIT: When adding another element to an array, you can just write it like this:

$test[] = 1;

If you need to merge two arrays, look at array_merge():

$test = array_merge($test, [1, 2, 3]);

Cheers!

Community
  • 1
  • 1
versalle88
  • 1,101
  • 1
  • 7
  • 19
  • ok , so if the index already exist, it doesn't goto next, it skip it ! That made it clear. Thx alot ! – MHX May 27 '15 at 19:28
  • @MHX No problem. Just be be clear, if you're merging two arrays using the plus sign (+), any indexes from the right array that already exist in the left will be skipped. If you add to an array (i.e., $test[] = 1) it will be added as the next index, and the internal pointer will be incremented. – versalle88 May 27 '15 at 19:36