Echoing Throughout Tel Numara Echoing Throughout Tel Numara - 11 months ago 40
PHP Question

PHP : Get or search values in_array from my variable and display it

I have array I'm checking if my variable has a value in that array. Also, get the same value as well. I need to add condition first, like for example if the variable 25 has a same value in my array $arr return true and display the array value array(2=>25)

$variable = 25;
$arr = array(1=>26, 2=>25 ,3 => 30 ,4 => 31, 5 => 32);

if(in_array($variable , $arr)){

//get the array value that have in array and display that array and preserve the key
//print_r($arr) -> 25


Answer Source

As you said:-

I mean search the value of variable into that array, If true, then display the 2=>25. Example if 25 has a value in array $arr , true. Then display 2=>25

You can do it like below:-


$variable = 25;
$arr = array(1=>26, 2=>25 ,3 => 30 ,4 => 31, 5 => 32);

$key = array_search($variable,$arr); // search the value and return the key
echo $key .'=>'.$arr[$key]; // echo both key and value based on key


Note:- if two values are identical in array and you are searching for that value,then the above code will give only first match not second-one