PHP array – foreach loop on values
<?php $a = array("v1", "v2", "v3"); foreach ($a as $val) { echo "$val "; } ?>
v1 v2 v3
Env: PHP 7.4.33 (Linux)
PHP array – foreach loop on index,values
<?php $a = array("v1", "v2", "v3"); foreach ($a as $idx => $val) { echo "$idx $val "; } ?>
0 v1 1 v2 2 v3
Env: PHP 7.4.33 (Linux)
PHP array – foreach loop for modification
<?php $a = array("v1", "v2", "v3"); foreach ($a as &$val) { $val = $val . "New"; } print_r($a); ?>
Array ( [0] => v1New [1] => v2New [2] => v3New )
Env: PHP 7.4.33 (Linux)
PHP associative array – foreach loop on values
<?php $a = array("k1"=>"v1", "k2"=>"v2", "k3"=>"v3"); foreach ($a as $val) { echo "$val "; } ?>
v1 v2 v3
Env: PHP 7.4.33 (Linux)
PHP associative array – foreach loop on keys,values
<?php $a = array("k1"=>"v1", "k2"=>"v2", "k3"=>"v3"); foreach ($a as $key=>$val) { echo "$key $val "; } ?>
k1 v1 k2 v2 k3 v3
Env: PHP 7.4.33 (Linux)