Skip to content
Advertisement

PHP Multidimenstional Associative Array Search by Value

I have an array where I want to search the name and get the key of the array that its associated to.

Examples

Assume we have the following 2-dimensional array with the second dimension being associated to a key:

$leaderboard = array(
    029102938093028 => array(
        'Rank' => '1st',
        'Name' => 'HenryB',
        'Kills' => 10,
        'Deaths' => 4,
        'Headshots' => 5
    ),
    029382912873929 => array(
        'Rank' => '2nd',
        'Name' => 'Edward B',
        'Kills' => 6,
        'Deaths' => 4,
        'Headshots' => 1
    ),
    0283928293898303 => array(
        'Rank' => '3rd',
        'Name' => 'Robert M',
        'Kills' => 3,
        'Deaths' => 10,
        'Headshots' => 0
    ),
);

The function call search_by_uid(“HenryB”) (name of the first user) should return 029102938093028 (The key of the array).

The function call search_by_uid(“Robert M”) should return 0283928293898303.

I have seen examples using multidemensional arrays where it returns the index but never the associated index. Please close if repeat question that i am unable to find.

Advertisement

Answer

$leaderboards = array(
    '029102938093028' => array(
        'Rank' => '1st',
        'Name' => 'HenryB',
        'Kills' => 10,
        'Deaths' => 4,
        'Headshots' => 5
    ),
    '029382912873929' => array(
        'Rank' => '2nd',
        'Name' => 'Edward B',
        'Kills' => 6,
        'Deaths' => 4,
        'Headshots' => 1
    ),
    '0283928293898303' => array(
        'Rank' => '3rd',
        'Name' => 'Robert M',
        'Kills' => 3,
        'Deaths' => 10,
        'Headshots' => 0
    ),
);

function search_by_uid($array, $name) {

    foreach ($array as $index => $value) {
        if($value["Name"] === $name) {
            return $index;
        }
    }

}

echo search_by_uid($leaderboards, 'Robert M'); //Returns 0283928293898303

Using a foreach loop to loop through all the values in the array until matching value is found, then the index is returned and the loop stops.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement