Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

php - Conditions Ignored - IF statement inside Foreach loop

so I am running through an array containing different types of fruit, by using foreach. Every time a fruit of that array matches a fruit within the string of $this-field (for example apples), the fruit shall get echoed.

Problem What happens instead is that this code will simply list EVERY fruit within $fruits. It does so even if I erase the whole strpos part and replace it by whatever I want like $test or something. It is like the conditioning within the if-loop is just getting totally ignored for some reason and I can't wrap my head around it. Please take a look at my code below.

foreach ($fruits as $fruit) {
    if (strpos($this->field('has_apples'), $fruit) !== false ) {
        echo $fruit;
    };
}

EDIT

$fruits = array("banana","apple","cherry"); 

The other one returns a string stemming from a blob like "kiwi,apple,coconut,orange". Does that help?

$this->field('has_apples')

...is returning a string from the table "has_apples", that will look like this: "banana,apple,cherry,coconut,walnut,watermelon".

For what ever reason if I just use this code, without running through the foreach-loop it works perfectly:

if (strpos($this->field('has_apple'), 'apple') !== false ) {
                    echo 'Yes, there is an apple inside the string';
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...