Udders
Udders

Reputation: 6976

in_array unexpected results

Hello I have an array that looks likes this,

    Array
(
    [0] => 40's
    [1] =>  50's
    [2] =>  60's
)

and some code that looks like this,

<?php if(isset($playable_age) && in_array('40\'s', $playable_age)) { $set = TRUE; } else { $set = FALSE; } ?>
<div class="checkbox"><?php echo $this->formbuilder->checkbox( 'playable_age[]', "40's", "40's", $set ); ?></div>
<?php if(isset($playable_age) && in_array('50\'s', $playable_age)) { $set = TRUE; } else { $set = FALSE; } ?>
<div class="checkbox"><?php echo $this->formbuilder->checkbox( 'playable_age[]', "50's", "50's", $set ); ?></div>
<?php if(isset($playable_age) && in_array('60\'s', $playable_age)) { $set = TRUE; } else { $set = FALSE; } ?>
<div class="checkbox"><?php echo $this->formbuilder->checkbox( 'playable_age[]', "60's", "60's", $set ); ?></div>

Now the first if statement returns true, however the 2nd and 3rd if return false even though the 50's and 60's values exist in the array why is this?

Upvotes: 1

Views: 113

Answers (3)

Sonal Khunt
Sonal Khunt

Reputation: 1894

Because you have a syntax error.

You can do this:

<?php 
$playable_age = array(0=>'40\'s',1=>'50\'s',2=>'60\'s');
if(isset($playable_age) && in_array('40\'s', $playable_age)) { $set = TRUE; echo "1"; } else { $set = FALSE; echo "2"; } 
if(isset($playable_age) && in_array('50\'s', $playable_age)) { $set = TRUE; echo "3"; } else { $set = FALSE; echo "4"; } 
if(isset($playable_age) && in_array('60\'s', $playable_age)) { $set = TRUE; echo "5"; } else { $set = FALSE; echo "6"; } 
if(isset($playable_age) && in_array('70\'s', $playable_age)) { $set = TRUE; echo "7"; } else { $set = FALSE; echo "8"; } 
?>

Upvotes: 0

Mina
Mina

Reputation: 737

Before you perform logic checks on the array, create a user-defined function and call it with array_walk to trim() on each array value.

Upvotes: 0

codaddict
codaddict

Reputation: 454990

Looks like there is a space before these values in the array:

[1] =>  50's
[2] =>  60's
       ^

Something not seen with the first value:

[0] => 40's

Upvotes: 4

Related Questions