jbowman99's avatar

multidimensional array searching to return key if value found

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

0 likes
1 reply
jbowman99's avatar
jbowman99
OP
Best Answer
Level 7

this did the trick

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


        foreach($radioreps as $key => $rep)
        {
            if (in_array($username, $rep)) {
                echo "Found {$rep['id']} for {$username}" . PHP_EOL;
                return $rep['id'];
            }
        }
        return false;

Please or to participate in this conversation.