0

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?!

1
  • Try trim($test) == 'One' Commented Apr 12, 2014 at 10:41

3 Answers 3

5

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);

i.e. 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, while the other suggestions are all valid as well, I liked this one as it was simple, to the point and explained what was going on.
1

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 strposenter 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 />";}}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.