Why does this change in assignment order change the variables contents?
-
23-10-2019 - |
Question
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]);
OTHER TIPS
1. $custId = $custId[1];
2. $serial = $custId[2]; // **
** this really means, ($custId[1])[2] of the original getExternalId();
Because the variable $custId after line 1 is no longer the result of
$custId = getExternalId();
But rather only the 2nd element (index [1]) from it.
You can add to your debugging by dumping just one more time
$custId = explode('_', $custId);
var_dump($custId);
$custId = $custId[1];
var_dump($custId);
$serial = $custId[2];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow