0

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';
2
  • 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. Commented Jul 7, 2013 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? Commented Jul 7, 2013 at 0:49

2 Answers 2

5

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

You could go for an array of excel_files too, that would probably be more valid.
0

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!";

2 Comments

Isset is not necessary, you can just if ( @$aux[ $extension ] )
You should use isset and remove the shut-up operator @. Good habit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.