简体   繁体   中英

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?

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

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"; } 
?>

在对数组执行逻辑检查之前,创建一个用户定义的函数并使用array_walk调用它以对每个数组值进行trim()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM