PHP: Finding a multi-dimensional array key’s associated value

I thought I would share this simple PHP function to hopefully help anyone needing a quick solution.

Imagine, you have a multi-dimensional array such as this:

<?php
    //Example array
    $array = array(
      'test' => array(
          'name' => 'John Doe',
          'email' => 'john@example.com'
      )
    );
?>

And you need to extract a specific bit of data, such as a name or an email address. You already know what the key name will be but require the value stored against it.

Run this function, pass the array and the name of key you’re searching for:

<?php
    /*
        Function: Find a key's value pair

        $array = The array data to look through
        $findKey = The Key name to be searched for. The value pair of this key will be returned.
    */
    function keyValue($array, $findKey) {

        //Loop through array
        foreach ($array as $key => $value) {
            
            //If the key of this current loop matched what we're looking for, return the value
            if ($key == $findKey) {
                $output = $value;

            //If still an array, it must be multi-dimensional, re-look through array
            } elseif (is_array($value)) {
                $output = keyValue($value, $findKey);
            }
        }

        return $output;
    }
?>

The result will return the value that was stored against the key. Here is a full code example:

<?php
    /*
        Function: Find a key's value pair

        $array = The array data to look through
        $findKey = The Key name to be searched for. The value pair of this key will be returned.
    */
    function keyValue($array, $findKey) {

        //Loop through array
        foreach ($array as $key => $value) {
            
            //If the key of this current loop matched what we're looking for, return the value
            if ($key == $findKey) {
                $output = $value;

            //If still an array, it must be multi-dimensional, re-look through array
            } elseif (is_array($value)) {
                $output = keyValue($value, $findKey);
            }
        }

        return $output;
    }



    //Example array
    $array = array(
      'test' => array(
          'name' => 'John Doe',
          'email' => 'john@example.com'
      )
    );

    //Run function
    echo keyValue($array, 'email');
?>
There are no comments, be the first. Use the form below to add your comment

Post a Comment