Jump to content

[SOLVED] return true or false with stripos


porta325

Recommended Posts

Hey guys, can anyone tell me how can i do to stop execution of a loop if one value returns true ?

Here is my script:

$aaa = ("08408041333118");

$bann = array("1","2","3","4");

 

for ($i=0; $i < count($bann);$i++){

 

if ($ban = stripos($aaa,$bann[$i])){

 

echo "-true";

}

else

{

echo "-false";

}

}

 

It returns -true-false-true-true , but i need the loop to stop when it finds the first occurence and only display "number found" only once outside the loop.

Link to comment
https://forums.phpfreaks.com/topic/79085-solved-return-true-or-false-with-stripos/
Share on other sites

Use "break":

 

<?php

$aaa = ("08408041333118");
$bann = array("1","2","3","4");

for ($i=0; $i < count($bann);$i++)
{
if ($ban = stripos($aaa,$bann[$i]))
{
	echo "-true";
	break;
}
else
	echo "-false";
}

?>

 

 

Keep in mind that using breaks is not a very "clean" way to terminate a loop- it can be sometimes unclear to someone who looks at your code and tries to understand what you did.

In this case it's pretty clear tho.

 

Orio.

You can do the same thing this way:

 

<?php

$aaa = ("08408041333118");
$bann = array("1","2","3","4");

$x = FALSE;
for ($i=0; $i < count($bann);$i++)
{
if ($ban = stripos($aaa,$bann[$i]) !== FALSE)
{
	$x = TRUE;
	break;
}
}

?>

 

This also fixes the little bug you had in your if.

 

Orio.

$aaa = ("08080");

$bann = array("1","2","3","4");

 

$x = FALSE;

for ($i=0; $i < count($bann);$i++)

{

if ($ban = stripos($aaa,$bann[$i]) !== FALSE)

{

$x = TRUE;

break;

}

}

if ($x = false){

echo "false";

}

else

{

echo "true";

}

 

this returns true when it should return false. Can't figure out why.I removed the true values from the first string.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.