0

We have an array of strings of numbers

$a = ["1", "2", "3"];

foreach loop doesn't change the type, result: [0]=>string(1) "1"

foreach ($a as $v) $v = (int) $v;

for loop makes ints from strings, result: [0]=>int(1)

for ($i = 0; $i < count($a); $i++) $a[$i] = (int) $a[$i]; 

Please, explain why is that?

toy boy
  • 105
  • 4

1 Answers1

1

The same reason that

$v = $a[0];
$v = int($v);

doesn't change $a. $v is a copy of the array element, not a reference to it.

You can make it work using a reference variable

foreach ($a as &$v) {
    $v = (int)$v;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612