I do not know if there is any justified reason to avoid using foreach
.
If you want other alternatives, apart from what @juan indicates, there are other alternatives, but I want to be clear that none is better than foreach
:
In alternatives 1 to 3 we will create the array as of JSON:
$strJson='
{
"llave1":"valor1","llave2":"valor2","llave3":"valor3"
}';
$arrayJson=json_decode($strJson);
1. Using array_walk
:
array_walk($arrayJson, function(&$v, $k) { $v = "$k: $v".PHP_EOL; echo $v;});
2. With while
and also using list
and each
That is, two additional functions .
while (list($k, $v) = each($arrayJson)) {
echo "$k: $v".PHP_EOL;
}
3. Using foreach
what you do not want precisely, but the best
This is the simplest and fastest:
foreach ($arrayJson as $k => $v) {
echo $k . ': ' . $v.PHP_EOL;
}
There must be a very justified reason for not wanting to use it:)
4. Using array_map
In this case, we are going to build the array from the JSON like this:
$arrayJson=json_decode($strJson,TRUE);
And we use array_map
combined with array_keys
. In the callback we print the keys and the values:
$callback = function ($k, $v) {
echo "$k: $v".PHP_EOL;
//return array($k => $k);
};
array_map( $callback, array_keys($arrayJson), $arrayJson);
In all three codes the output is the same:
Exit:
llave1: valor1
llave2: valor2
llave3: valor3