jbowman99
1971
1
Laravel

multidimensional array searching to return key if value found

Posted 2 years ago by jbowman99

I need to pass in a name to a search function on an array. If then name is found I need to return the key associated with the value.

this was my first pass, with an array and it works

$radioreps = [
            '7' => 'Larry',
            '8' => 'Kelly',
            '9' => 'Dave',
            '10' => 'Dana',
            '11' => 'Silver',
            '12' => 'Lueth',
            '17' => 'Mike',
            '34' => 'Ennen',
        ];

        if(in_array($username, $radioreps)) {
            $key = array_search($username, $radioreps);
            return $key;
        }

        return false;

although the value being passed in might be a first or last name, so i needed to associate multiple names to one key.

like so:

$radioreps = array(
            '7' => array('Larry', 'Fredrickson'),
            '8' => array('Kelly', 'Steve'),
            '9' => array('Dave', 'David', 'Burns'),
            '10' => array('Dana', 'Burress'),
            '11' => array('Silver', 'Marsha'),
            '12' => array('Elaine', 'Lueth'),
            '17' => array('Mike', 'Haile'),
            '34' => 'Ennen',
        );

foreach($radioreps as $rep){
            if(($strict ? $rep === $username : $rep == $username) || (is_array($rep) && in_array($username, $rep, $strict))) {
                $key = array_keys($rep);
                dd($key);
                return $key;
            }
        }
        return false;

not sure i'm doing this right though. but i want my end results to be if Fredrickson is passed in, then the key 7 should be returned, and so on.

More of a PHP questions than a laravel question. Sorry about that

Please sign in or create an account to participate in this conversation.