peke_peke
peke_peke

Reputation: 551

search array for key PHP

function returnStatus($status)
{
    $supportStatus = [
        0 => 'open',
        1 =>'half closed',
        9 => 'closed',
    ];

    $key = array_search($status, $supportStatus);
    return $supportStatus[$key];
}

My script returns 0 (open), even if I sent 9 as int to the function.

Upvotes: 0

Views: 39

Answers (2)

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13948

What you are looking for is the array_key_exists()

function returnStatus($status){

    $supportStatus = [
        0 => 'open',
        1 =>'half closed',
        9 => 'closed',
    ];

    $key = array_key_exists($status, $supportStatus);
    return $supportStatus[$key];
}

Furthermore you donot even need to do that jugglery, if eventually you are interested in the value stored in that key's location.

I'd just do it in one line as below..

echo isset($supportStatus[$status]) ? $supportStatus[$status]: false;

or with assignment operator

$output = isset($supportStatus[$status]) ? $supportStatus[$status]: '';

Upvotes: 1

Nikhil
Nikhil

Reputation: 1450

I hope this is what you're looking for,

function searchColor($color){
    $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
    $key = array_search($color, $array); 
    return $array[$key];    
}
echo searchColor('blue');

Update your code and see if it works, here is the reference.

Upvotes: 0

Related Questions