简体   繁体   中英

PHP - If statement within foreach

So I'm brand new to PHP and am trying to accomplish something pretty simple. Import a text file to an array, have a foreach go through that array looking for a value, and printing the value if found.

Here is what I have tried so far:

$testers = file('test.txt');
foreach ($testers as $test) {echo $test . "<br />";}

This works great, each line is printed. Perfect. I then add an IF statement.

$testers = file('test.txt');
foreach ($testers as $test) {if ($test){echo $test . "<br />";}}

Also working fine, seems to be returning data. Now if I try and add an operator, it all falls apart.

$testers = file('test.txt');
foreach ($testers as $test) {if ($test == "One"){echo $test . "<br />";}}

I should say, the text file has in it numbers on each line from "One" to "Six" I also tried:

$testers = file('test.txt');
foreach ($testers as $test) {if ($test === "One"){echo $test . "<br />";}}

This also returned nothing...

Any insight would be awesome! Thanks!

What exactly am I missing here? Why is this if statement not returning the value I'm looking for?!

Your problem is because file() by default will include line breaks into each line. Thus, comparison on equality will fail.

You may use:

$testers = file('test.txt', FILE_IGNORE_NEW_LINES);

ie add flag so PHP won't include line breaks to resulting array items.

If you don't want to list empty lines, there's corresponding FILE_SKIP_EMPTY_LINES flag, so:

$testers = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

You should use stripos() to make the check instead and do an array_filter prior to that to remove empty entries from your $testers array.

The code...

<?php
$testers = array_filter(file('test.txt'));
foreach ($testers as $test) {if (stripos($test,"One")!==false){echo $test . "<br />";}}

If you want to compare each line if it's equal to another, please check about strcmp

If you want to see if a line contains a string, please check strpos enter link description here

for strcmp :

foreach ($testers as $test) {if (strcmp($test,"one")==0){echo $test . "<br />";}}

for strpos:

foreach ($testers as $test) {if (strpos($test,"one") !==false){echo $test . "<br />";}}

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