Jump to content

if inside foreach loop not working


Stargate22
Go to solution Solved by Barand,

Recommended Posts

Hello guys 

$myFile = "smt.txt";
$fh = fopen($myFile, 'r');
$all = fread($fh, filesize($myFile));
$cities = explode ("," , $all);

foreach ($cities as $city) {
        if(0 === strpos($city,'E')){
	    print_r($city);
	}
}

I want to print only the strings from the array $cities that start with E , my code does nothing, not an error, nothing.. if i remove the if and let the print it works.. but I need just thous that start with E.

Do you guys have any tips?

PS: in my array there are a lot of cities that start with E...

Thank you!

Link to comment
Share on other sites

Just show the output of this:

var_dump($cities);

We want to verify that there is a value that starts with 'E' (not 'e') and that the value doesn't start with a space or some other non-printable character.

Hello,

It prints the array cities like:

array (size=268)

0 => string 'Aboed' (length=5)

1 => string '

Ajold' (length=7)

2 => string '

Afed' (length=6)

3 => string '

... etc

Eugir' (length=7)

82 => string '

Eurtici' (length=9)

83 => string '

.. etc

foreach ($new as $city) {
	$findme = "E";
        $pos2 = strpos($city, $findme);
	#if($pos2 !== false){
             #echo "<li>$city</li>";		
        }
}

^-> above code prints all cities that start with E... but why is my initial code not workin`?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.