Hassan
Hassan

Reputation: 2843

PHP : Get key of an array that matches specific value

Here is how I set my Array:

 $Post_Cat_Array = array();
 while($row = mysql_fetch_array( $result )) {
 $Post_Cat_Array[$row['type_id']] = $row['type_name'];}

in this function I need to get the type_id(key) of a specific type_name(value)

function NameToID($input){
echo array_search($input, $Post_Cat_Array); 
}

and I call the function like this :

NameToID($_POST['type']);

But it's not working. It doesn't echo anything. I am sure the $_POST['type'] contains correct value.

note:value of $_POST['type'] is in arabic. same with all values of the array.

Upvotes: 0

Views: 288

Answers (2)

Hanky Panky
Hanky Panky

Reputation: 46900

That is because your array variable is not known to your function. You can use either of the following to achieve that

<?php
$Post_Cat_Array=array();
$Post_Cat_Array["key1"]="value1";
$Post_Cat_Array["key2"]="value2";
$Post_Cat_Array["key3"]="value3";
$Post_Cat_Array["key4"]="value4";

echo NameToID("value4");
echo "<br>";
echo NameToID2("value4",$Post_Cat_Array);

function NameToID($input){ 
    global $Post_Cat_Array;
    echo array_search($input, $Post_Cat_Array);  
} 
function NameToID2($input,$values){ 
    echo array_search($input, $values);  
} 
?>

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27594

It seems that $Post_Cat_Array is out of scope. Modify your function:

function NameToID($input, $arr){
  echo array_search($input, $arr); 
}

and then:

NameToID($_POST['type'], $Post_Cat_Array);

From PHP Variable scope:

This script will not produce any output because the echo statement refers to a local version of the (...) variable, and it has not been assigned a value within this scope.

Upvotes: 1

Related Questions