How to use array_walk function In PHP

The array_walk function applies a user-defined function to every element of the array. This method can be used to access both keys and values of an associative array.

Example : Using array_walk function to access the keys of an associative array

PHP
<?php
// Use array_walk() function to display 
// the key of associative array

// Associative array
$assoc_array = array(
    "Alpha" => 1, 
    "Beta" => 2, 
    "Gamma" => 3 
);

// User-defined function to display keys
function display_key($value, $key) {
    echo "key: " . $key . "\n";
}

// Applying array_walk function
array_walk($assoc_array, 'display_key');
?>

Output
key: Alpha
key: Beta
key: Gamma

How to loop through an associative array and get the key in PHP?

Associative arrays are used to store key-value pairs. For example, to store the marks of the different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. In associative array, the key-value pairs are associated with => symbol.

here are some common approaches:

Table of Content

  • Using for-each loop
  • Using array_keys() function
  • Using array_walk function

Similar Reads

Using for-each loop

In this method, traverse the entire associative array using each loop and display the key elements....

Using array_keys() function

The array_keys() is an inbuilt function in PHP which is used to return either all the keys of array or the subset of the keys....

Using array_walk function

The array_walk function applies a user-defined function to every element of the array. This method can be used to access both keys and values of an associative array....

Contact Us