Skip to main content
PHP

Does a variable inside the loop retain its value in PHP?

By May 31, 2021No Comments

The following is the code to put this to test.

1
2
3
4
5
6
7
8
9
10
11
12
$something = true;

$array = array('a', 'b', 'c', 'd');

foreach ($array as $a) {

    var_dump($a);
    var_dump($something);

    $something = false;

}

Here’s the output.


1
2
3
4
5
6
7
8
string(1) "a"
bool(true)
string(1) "b"
bool(false)
string(1) "c"
bool(false)
string(1) "d"
bool(false)