The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.
Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.
So as we can see in the example above, we can easily loop through indexed array using for loop. But for Associative Arrays we need to use ForEach loop.
You can do:
foreach ($arr as $key => $value) {
echo $key;
}
As described in PHP docs.
If you use array_keys()
, PHP will give you an array filled with just the keys:
$keys = array_keys($arr);
foreach($keys as $key) {
echo($key);
}
Alternatively, you can do this:
foreach($arr as $key => $value) {
echo($key);
}
Nobody answered with regular for
loop? Sometimes I find it more readable and prefer for
over foreach
So here it is:
$array = array('key1' => 'value1', 'key2' => 'value2');
$keys = array_keys($array);
for($i=0; $i < count($keys); ++$i) {
echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}
/*
prints:
key1 value1
key2 value2
*/
foreach($array as $k => $v)
Where $k is the key and $v is the value
Or if you just need the keys use array_keys()
I use the following loop to get the key and value from an associative array
foreach ($array as $key => $value)
{
echo "<p>$key = $value</p>";
}
The following will allow you to get at both the key and value at the same time.
foreach ($arr as $key => $value)
{
echo($key);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With