简体   繁体   中英

check if value exists in a multidimensional array and get item's key

I'm trying to classify file extensions with this function.

function extClass($ext){
    $extClasses = array(
        'archive' => array('7z', 'cbr', 'deb', 'gz', 'pkg', 'rar', 'rpm', 'sitx', 'tar.gz', 'zip', 'zipx'),
        'web' => array('php', 'js', 'css', 'asp', 'aspx', 'htm', 'html', 'cc', 'cpp', 'py', 'jsp'),
        'text' => array('txt', 'doc', 'docx', 'log', 'rtf'),
    );
    foreach($extClasses as $key=>$extClass){
        return in_array(strtolower($ext), $extClass) ? $key : false;
    }
}

The result of extClass('txt') is false instead of text . It seems that value txt is not found in this multidimensional array. How could I make it right?

You don't loop over all elements in the foreach. On the first loop you return either $key or false, so it doesn't check other indexes.

Working code:

function extClass($ext){
    $extClasses = array(
        'archive' => array('7z', 'cbr', 'deb', 'gz', 'pkg', 'rar', 'rpm', 'sitx', 'tar.gz', 'zip', 'zipx'),
        'web' => array('php', 'js', 'css', 'asp', 'aspx', 'htm', 'html', 'cc', 'cpp', 'py', 'jsp'),
        'text' => array('txt', 'doc', 'docx', 'log', 'rtf'),
    );
    foreach($extClasses as $key=>$extClass){
        if (in_array(strtolower($ext), $extClass)){ // Return only if found during the loop
           return $key;
        }
    }
    return false; // If nothing found, return false
}

You are returning from the function prematurely.. You need to check using condition,so change your foreach like this

 foreach($extClasses as $key=>$extClass){
        if(in_array(strtolower($ext), $extClass))
        {
            return $key;
        }
    }

Demo

Try this:

  function extClass($ext){
    $extClasses = array(
        'archive' => array('7z', 'cbr', 'deb', 'gz', 'pkg', 'rar', 'rpm', 'sitx', 'tar.gz', 'zip', 'zipx'),
        'web' => array('php', 'js', 'css', 'asp', 'aspx', 'htm', 'html', 'cc', 'cpp', 'py', 'jsp'),
        'text' => array('txt', 'doc', 'docx', 'log', 'rtf'),
    );
    foreach($extClasses as $key=>$extClass){ print_r($extClass); 
        if (in_array(strtolower($ext), $extClass)) {
            return $key;
        }
    }

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM