简体   繁体   中英

in_array not working as expected

So i have a very simple snippet. I studied the in_array command and found it would be what i need.

However its not working?

I have tried several scenarios:

$this->item->tour_days is an array containing 1,2,3

test 1

    $days = $this->item->tour_days;

    $array = array($days);

    if (in_array(2,$array,TRUE)) {

    echo 'Tuesday';

    } 

test 2

    $days = $this->item->tour_days;

    $array = array($days);

    if (in_array(2,$array)) {

    echo 'Tuesday';

    } 

test 3

    $days = $this->item->tour_days;

    $array = array($days);

    if (in_array('2',$array)) {

    echo 'Tuesday';

    } 

I have tried to echo Tuesday where Tuesday = 2 from my csv but no luck.

Thanks in advance for nay help here jonny

要将包含逗号分隔列表的字符串转换为数组,请使用explode

$array = explode(',', $days);

尝试这个:

$array = explode(",",$days);

$this->item->tour_days is an array containing 1,2,3

Then why do you want to make another array out of it?

remove the $array = array($days); converstion.

Instead say $array = $days;

This should work for you:

If $days is a string then use this:

    $days = "1,2,3";  //$this->item->tour_days;

    $array = explode(',', $days);

    if(in_array(2, $array))
        echo "Tuesday";


?>

If $days is already an array use this:

<?php

    $days = array(1,2,3);  //$this->item->tour_days;

    if(in_array(2, $days))
        echo "Tuesday";


?>

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