Join my Laravel for REST API's course on Udemy 👀

Loop through the keys of a PHP array

April 26, 2022  ‐ 1 min read

In most cases you probably want to loop over the values in an array. But in some cases you want to loop over the keys as well. In my case this happened when writing data to a CSV file and I used the keys for the column headers.

Probably the most convenient way is by using the array_keys() array function. This function takes an array as its argument and returns an array of the keys you used. Next you can loop over that returned array as you would with any other array.

<?php

$values = [
  'user' => 1,
  'language' => 'nl'
];

$keys = array_keys($values);
// keys => ['user', 'language']

foreach ($keys as $key) {
  //
}

Another option would be to use the foreach loop with a key value pair, which would give you both the key and the value at each iteration of the for loop.

<?php

$values = [
  'user' => 1,
  'language' => 'nl'
];

foreach ($values as $key => $value) {
  //
}