Lewis
Lewis

Reputation: 14926

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?

Upvotes: 0

Views: 967

Answers (3)

Noman Ghani
Noman Ghani

Reputation: 468

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;
}

Upvotes: 0

Nambi
Nambi

Reputation: 12040

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

Upvotes: 2

naab
naab

Reputation: 1140

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
}

Upvotes: 2

Related Questions