0

I have this object:

$boosts = array(
    "2x12" => 500,
    "2x24" => 800,
    "2x7d" => 4500,
    "3x12" => 700,
    "3x24" => 1300,
    "3x7d" => 6500
);

And then a variable: $type = "2x12"; What I want to do is check in a loop if the variable $type exists in $boosts. I tried a lot of codes but I couldn't get it.

foreach ($boosts as $savedTypes) {
    echo json_encode($savedTypes) . "|";
    if ($boosts[$type] === $type) {
        echo "VALID";
    }
}
2
  • 1
    array_key_exists( $key, $arr )? Commented Dec 29, 2017 at 15:12
  • Thanks @RamRaider but I wanted to do it with the foreach loop. I'll use Ram's answer but thanks anyways :D Commented Dec 29, 2017 at 15:16

2 Answers 2

3

Unless I'm missing something you ought to be able to use array_key_exists in this instance

$boosts = array(
    "2x12" => 500,
    "2x24" => 800,
    "2x7d" => 4500,
    "3x12" => 700,
    "3x24" => 1300,
    "3x7d" => 6500
);
$type='2x12';
$valid=array_key_exists( $type, $boosts );
echo $valid ? 'VALID' : 'INVALID';
Sign up to request clarification or add additional context in comments.

Comments

1
foreach ($boosts as $key=>$value) {  
   if ($key === $type) {
    echo "VALID";
   }
 }

Hope this will help you

Comments

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.