Reputation: 14926
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
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
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;
}
}
Upvotes: 2
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