Reputation: 1145
I have an array which has several keys, each may be true/false:
$hide[1] = false;
$hide[2] = false;
$hide[3] = true;
I want a <div>
block to appear in my HTML if at least one key is set to true
:
<?php if ($some_condition_here==true) { ?>
<div>show me if at least one value is "true"</div>
<?php } else { } ?>
What is the best practice to do this, considering that sometimes I don't know in advance how many keys I may have (in this example, 3, though might be more). I can assume that max number will be about 20 though.
I'm not sure how to do this, since I don't know how to use loop
with if
, and also it needs to stop checking on the first event it finds a true
.
Upvotes: 0
Views: 209
Reputation: 3351
You are looking for the function in_array
, which checks if a certain value is in an array.
if( in_array( TRUE, $hide ) )
{
echo '<div>show me if at least one value is "true"</div>';
}
It also seems like you don't know how functions work. You might want to read about them: http://php.net/manual/en/language.functions.php.
Even without in_array
it would've been possible to implement it yourself by using a custom made function. That's essentially how you can use a loop with an if. Not recommended in this case, since we already know there's a function which does exactly what you need. I just included the example below for your education, NOT to be used. Use in_array
like in my first example!
function my_custom_in_array( $needle, $stack )
{
foreach( $stack as $v )
{
if( $v === $needle )
{
return TRUE;
}
}
return FALSE;
}
if( my_custom_in_array( TRUE, $hide ) )
{
echo '<div>show me if at least one value is "true"</div>';
}
Upvotes: 2
Reputation: 539
You should use the in_array()-function for this!
It checks if the first argument (true) is an your array ($hide). And it stops immediately when the first true is found.
Just put it in an if()-Statement and enjoy!
if( in_array(true, $hide) )
{
echo '<div> show me if at least one value is "true" </div>';
}
The code in the braces will only be executed if your array has at least one true in it!
Upvotes: 0
Reputation: 658
if(in_array(true,$hide)){
echo '<div>show me if at least one value is "true"</div>';
}
Upvotes: 1
Reputation: 54831
Check for true
value in array:
if (in_array(true, $hide)) { /* do something */ }
Upvotes: 1