Home > Software design >  Check if a value exists multidimensional array and return its key
Check if a value exists multidimensional array and return its key

Time:02-24

I have an array, say

$updates = array();
$updates['U1'] = array('F1', 'F2', 'F5');
$updates['U2'] = array('F3');
$updates['U3'] = array('F3', 'F4');

I need search for a value say F5 so it should return the key U1.

And also if there is multiple occurrence of a value, should return the last key.

Eg. searching F3 should return U3 and not U2.

I have searched a lot and can't find a way. I am looking for a solution without using loops.

CodePudding user response:

without using loop:

function findArrVal($arr = [], $param){
        static $indx = 0;
        if($indx == 0){
            krsort($arr);
        }
        
        $keys = array_keys($arr);
        $values = array_values($arr);
        
        if( count($values) == $indx ){
            return false;
        } else if( is_array($values[$indx]) && in_array($param, $values[$indx])){
            return $keys[$indx];
        } else {
              $indx;
            return findArrVal($arr, $param);
        }
        return FALSE;
    }

using loop:

function findArrVal($arr = [], $param){
        krsort($arr);
        foreach($arr as $key => $ar){
           if(is_array($ar) && in_array($param, $ar)){
               return $key;
           } 
        }
        return FALSE;
}
    
findArrVal($updates,'F3');
  1. krsort - sorts the array in reverse order. ( to find the value at first occurrence )
  2. is_array to check if the child value is an array type.
  3. in_array to find the item on the child array.

CodePudding user response:

Maybe It's helpful for you.

function _getFindArrayKey(array $arr, $key)
{
    if (array_key_exists($key, $arr)) {
        return true;
    }
    // check arrays contained in this array
    foreach ($arr as $element) {
        if (is_array($element)) {
            if (_getFindArrayKey($element, $key)) {
                return true;
            }
        }
    }

    return false;
}
  • Related