Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to get the key from an array by searching for its value. In the following code, what I don't understand is why array_search() can't find the key when the $url file extension is "xls" but it can when it is "php". I've noticed a similar issue of not being able to "find" "xls" using in_array() and array_keys().

$url='http://mysite.com/hello.xls';
$url='http://mysite.com/hello.php';

$extension_arr=pathinfo($url);
$extension=strtolower($extension_arr['extension']);

$arr=array(
    'excel_file'=>'xls', 
    'excel_file'=>'xlsx',
    'php_file' =>'php'  
  );

$array_search_key=array_search($extension, $arr);
if($array_search_key !== false){
  echo $array_search_key;
}
else echo 'crap';
share|improve this question
1  
You need to flip the keys and values of the array, it's not possible to associate more than one value with a given key. You can use isset() to perform the function you require when the keys and values are swapped. –  DaveRandom Jul 7 at 0:46
 
@DaveRandom thanks. It looks like this can also be solved by giving each key its own unique value, so something like 'excel_file xls' and 'excel_file xlsx'. Would you mind making an answer flipping the keys and values? –  tim peterson Jul 7 at 0:49

2 Answers

up vote 1 down vote accepted

Your search works, but the array you're searching is flawed. Element 1 (xlsx) overwrites element 0, because the keys are the same.

$arr=array(
  'excel_file'=>'xls', 
  'excel_file'=>'xlsx',  // This overwrites the line above.
  'php_file' =>'php'  
);

Flip the elements around and then you can just check if the key exists:

$arr=array(
  'xls'=>'excel_file', 
  'xlsx'=>'excel_file',  
  'php'=>'php_file'  
);

if (isset($arr[$extension])) {
   // do stuff
   echo $arr[$extension];
}
share|improve this answer
 
You could go for an array of excel_files too, that would probably be more valid. –  max_ Jul 7 at 1:39

First try to debug the $extension if its display the wanted value (xls), try to swap the key and the val, and try to find by new key:

$aux = array();

foreach( $arr as $key => $val )
{
    $aux[ $val ] = $key;
}

so you try to find the current value:

if ( isset( @$aux[ $extension ] ) ) echo "I found the current extension";
else "extension not found!";
share|improve this answer
 
Isset is not necessary, you can just if ( @$aux[ $extension ] ) –  scel.pi Jul 7 at 1:00
3  
You should use isset and remove the shut-up operator @. Good habit. –  apartridge Jul 7 at 1:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.