phpzend-server-ce

Why does this change in assignment order change the variables contents?


Explain this please :)

If I run

$custId = getExternalId();
echo $custId . "\n"; // Prints foobar_16262499_1
$serial = '';

$custId = explode('_', $custId);
var_dump($custId);
$custId = $custId[1];
$serial = $custId[2];

die("custId: $custId serial: $serial\n");

I get

custId: 16262499 serial: 2

This is not correct. Serial should be 1. But if I change the order of assignment to

$custId = getExternalId();
echo $custId . "\n"; // Prints foobar_16262499_1
$serial = '';

$custId = explode('_', $custId);
var_dump($custId);
$serial = $custId[2];   // Change order here!!!
$custId = $custId[1];

die("custId: $custId serial: $serial\n");

It works and gives me

custId: 16262499 serial: 1

WHY?

In both cases the var_dump of the array produces the same output:

array(3) {
  [0]=>
  string(4) "foobar"
  [1]=>
  string(8) "16262499"
  [2]=>
  string(1) "1"
}

I'm running PHP/5.3.3 ZendServer

SMACKS HEAD... How could I miss the obvious :)...


Solution

  • you override

    $custId 
    

    when you write this line

    $custId = $custId[1];
    

    so after that you get something you do not expect

    $serial = $custId[2];
    

    so do like this

    list($custId,$serial) = array($custId[1],$custId[2]);