php - What is the difference between these two array Iterations? -
i'm studying php advanced exam. practice test said first iteration better second. not figure out why. both iterate contents of array fine.
// first one:
foreach($array $key => &$val) { /* ... */ }
// second one:
foreach($array $key => $val) { /* ... */ }
the practice test said first iteration better second.
that isn't best advice. they're different tools different jobs.
the &
means treat variable reference opposed copy.
when have variable reference, similar pointer in c. accessing variable lets access memory location of original variable, allowing modify value through different identifier.
// variable. $a = 42; // reference $a. // & operator returns reference. $ref = &$a; // assignment of $ref. $ref = "fourty-two"; // $a has changed, through // reference $ref. var_dump($a); // "fourty-two"
reference example on codepad.
the normal behaviour of foreach
make copy available associated block. means free reassign it, , won't affect array member (this won't case variables references, such class instances).
copy example on codepad.
class instance example on codepad.
using reference in foreach
has side effects, such dangling $val
reference last value iterated over, can modified later accident , affect array.
dangling reference example on codepad.
Comments
Post a Comment