Home > database >  Using the key not value in a callback function part of array_walk in php
Using the key not value in a callback function part of array_walk in php

Time:10-26

In a situation such as this one:

array_walk($first_names, function($item) {
        // do something with the key not the value
    }
);

How can I extract the $item key to use? It's passed as the string value of the $first_names item, but inside the callback function, I would like to use the key not the value. Any ideas?

CodePudding user response:

Just like its mentioned in the PHP documentation here https://www.php.net/manual/en/function.array-walk.php

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

So array_walk($first_names, function($item) {

should be array_walk($first_names, function($value, $key) {

  •  Tags:  
  • php
  • Related