I have a JSON that is easy to traverse with a foreach, the structure of the JSON is as follows:
{
"llave":"valor","llave":"valor","llave":"valor"
}
foreach ($arrayJson as $key => $value) {
echo $key . ': ' . $val;
}
I would like to know if there is a way to extract keys and values with a for loop in PHP.
I don't 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 state that none is better than
foreach
:In alternatives 1 to 3 we will create the array like this from the JSON:
1. Using
array_walk
:2. With
while
and using in additionlist
andeach
That is, two additional functions .
3. Using
foreach
what you don't exactly want, but the bestThis is the simplest and fastest:
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:
And we use
array_map
combined witharray_keys
. In the callback we print the keys and values:In all three codes the output is the same:
Departure:
You can use the each function