awild
awild

Reputation: 49

How to check if a variable is in an array and then have it equal something in that array

If I have an array like:

[{"tierId":0,"tierName":"Blue"},{"tierId":1,"tierName":"Green"}]

how do I check if my variable = tierName and if it does have it equal the tierId. So if my variable is Green I want the same variable to equal 1. I tried:

$parsed = (array) json_decode($body->getContents()); 
if (in_array($start, $parsed)){
        $start == $parsed['tierId'];
    }

Upvotes: 0

Views: 95

Answers (2)

Barmar
Barmar

Reputation: 782409

There's no built-in function that searches a 2-dimensional array like that, you have to write a loop.

$parsed = json_decode($body->getContents(), true); // true makes it return arrays instead of objects
foreach ($parsed as $item) {
    if ($item['tierName' == $start) {
        $start = $item['tierId'];
        break;
    }
}

Upvotes: 0

Syed Imran Ertaza
Syed Imran Ertaza

Reputation: 175

if you want to find the key to match with the variable you can use this array_key_exists() function. Like this below

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>

And once the key match with your variable, you can also check if it is match with the value of that array key.

Also if you want to find a variable is exist or not into your array. You can use this in_array() function.

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}

Hope this will help you figure out solution.

Upvotes: 1

Related Questions