Cycle with foreach (interrupt)

Hi E's, In snippet code I put a example of a foreach. That will output:
All sequence is 1
Sequence without number 1
All sequence is 2
Sequence without number 2
All sequence is 3
Sequence without number 3
All sequence is 4
Sequence without number 4

What I want to do is, if the value of $arr is = $number the system don't print this line:
echo "Sequence without number $number";

And if $number = 3, the input will be:
All sequence is 1
Sequence without number 1
All sequence is 2
Sequence without number 2
All sequence is 3
All sequence is 4
Sequence without number 4

How I check if $number is = $arr, don't print the echo, and continue to number four or more.....

Regards, JC
$arr = array(1, 2, 3, 4, 5);
$number = 3;
foreach ($arr as $value) {
echo "All sequence is $value";
//WHAT I PUT HERE
echo "Sequence without number $number";
}

Open in new window

LVL 3
Pedro ChagasWebmasterAsked:
Who is Participating?
 
Roger BaklundConnect With a Mentor Commented:
>> if it is for more then 1 word?

Then you can use strpos(), as shown above in http:#a24773671

Note that it will also find partial words, for instance "peace" will be found in "so peacefull" and "ample" will be found in "example". If you need to match full words only, use explode() and in_array():

$words = 'my example';
$wordlist = explode(' ',$words);
if(in_array('ample',$wordlist)) echo 'ample was found';
if(in_array('example',$wordlist)) echo 'example was found';

In this example, "ample" would not be found, but "example" would be found.

Using explode() and in_array() also works if the $words string contains just a single word.
0
 
Roger BaklundCommented:
Use the expression ($value!=$number), like this:
$arr = array(1, 2, 3, 4, 5);
$number = 3;
foreach ($arr as $value) {
echo "All sequence is $value";
if($value!=$number)
  echo "Sequence without number $number";
}

Open in new window

0
 
Pedro ChagasWebmasterAuthor Commented:
hI @cxr, thanks for your feedback.
Maybe my question is incomplete....
And if array as compose by words and not numbers like:
$arr = array(million, sea, peace cake, rock roll, something);
$number = peace;

Regards, JC

0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Roger BaklundCommented:
It works the exact same way, but remember to use apostrophes or quotes for constant strings in PHP:

$arr = array('million', 'sea', 'peace cake', 'rock roll', 'something');
$number = 'peace';

In this case, 'peace' will not be found, because it is not one of the items in the array ('peace cake' is a different value).

If you want to find a substring within a string, you can use the strpos() function:

if(substr($value,$number)!==false)

http://php.net/strpos
0
 
Roger BaklundCommented:
Sorry, I wrote substr when I meant strpos...

if(strpos($value,$number)!==false)
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @cxr, why '!==false'? Why you don't use '==true'?

Regards, JC
0
 
Roger BaklundCommented:
Because that function does not return the boolean value "true". It returns an integer: the position of the $number within the $value. In this test case, it would return 0 (zero), because "peace" is at the beginning of the string "peace cake". (0==true) is false, it would not find it. However, (0!== false) is true. Note the double ==, needed in this case because (0!=false) is false, and (0==false) is true. This is because PHP has a loose type system, integer 0 is evaluated as boolean false when using == or != operators and comparing with a boolean value. !== and === requires that both operands are of the same type to be considered equal.
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @cxr, I try to do this solution in my real code and don't work. Maybe the problem are apostrophes or quotes.
The array I use to do the foreach give me this output:
Array
(
    [0] => banco
    [1] => world
    [2] => dw
    [3] => lista
    [4] => download
    [5] => digital
    [6] => dvd
    [7] => wallpaper
    [8] => dinheiro
    [9] => brasil
    [10] => video
)

Explain My code:
The objective of my code is made a cycle in array with foreach, and save each word and scores in database.
The variable $palavradb is the variable that contain the word or words to check if exist inside array, if exists the script interrupt and don't save in database, and continue in foreach, if not, the script continue. $palavradb is the variable that I use inside strpos: if(strpos($nomek,$palavradb)!==false)

Because I have two kinds of scores, one for $palavra = 1 word, and other for $palavradb => 2 words, I use $n_palavras_b and this variable contain the size of $palavradb (the first line in snippet code).

$keysrel_numeracao contain the array with the score and $keysrel_nomeinverte contain the word

I will check if word exists in database, if exists the script update, if not exists the script insert.
=========================================

I try use strpos but don't work, maybe you can help and tell me where I put the function strpos in my two foreach ($n_palavras_b = 1 or $n_palavras_b = 2 or more words inside $palavradb).

So, how I interrupt the foreach when the system discover equal words?
Note: interrupt just that foreach, the foreach continue for the next word!

Regards, JC

if ($n_palavras_b == 1){//1000  //se for só uma palavra
	$nmin = 10; //grava a partir de 10 valores
	//adquire 2 arrays, uma com os nomes e outra com os pontos
	$keysrel_nomeinverte = $keysrel; //adquire a array 
	$keysrel_nomeinverte = array_keys($keysrel_nomeinverte); //inverte os valores
	$keysrel_numeracao = $keysrel;
	$keysrel_numeracao = array_filter(array_values($keysrel_numeracao), create_function('$item','global $nmin; return $item>=$nmin;'));
	
	//inicia o sistema para checar palavra a palavra
	$contador = 0;
	foreach ($keysrel_numeracao as $valor) { //2000 //por cada palavra autorizada faz o tratamento individual 
	$nomek = $keysrel_nomeinverte[$contador];
	$existek_result = mysql_query("SELECT * FROM keywords where keyword = '$nomek'", $db);
	$existek_rows = mysql_num_rows($existek_result);
	$existek = mysql_fetch_object($existek_result);
	//pontuacao maxima
		if($existek_rows == 1){ //3000  //se já existir uma linha
			$pontuacaodb = $existek->pontuacao_maxima;
			if($pontuacaodb < $valor){ //4000 //se o valor novo for mais alto do que lá está na bd
				$pontuacao_max = $valor;
					} else {
						$pontuacao_max = $pontuacaodb;
						} //F4000
	//tres_pontos
	$value = "$existek->tres_pontos";
    $numbers = explode(' ',$value);
    $new_number = $valor;
    if(strlen($new_number)<2)        # if less than two digits...
    $new_number = '0'.$new_number; # ...prefix with a 0 
    $numbers[] = $new_number;
    sort($numbers);
    while(count($numbers) > 3)  # if more than 3 numbers
    array_shift($numbers);    # remove smallest number
    $new_value = implode(' ',$numbers);
    echo "<br>NEW $new_value";
	//tres_pontos_min
	$tres_pontos_min = $numbers[0];
	//tres_pontos_media
	$media_tres_pontos = array_sum($numbers) / 3;
	//media todos_resultados
	$media_resultados = $existek->todos_resultados; //saca a string
	$media_resultados = explode(' ', $media_resultados); //converte em array
	array_push($media_resultados, "$valor"); //introduz uma nova key com o valor actual
	$n_chaves = count($media_resultados); //verifica quantas chaves existem
	$media_total = array_sum($media_resultados); //soma todos os valores da array
	$media_resultados_total = $media_total / $n_chaves; //arranja a media 
	//todos resultados
	$sql = "UPDATE keywords SET todos_resultados= CONCAT('" . mysql_real_escape_string($valor) . "', ' ', todos_resultados), pontuacao_maxima = '$pontuacao_max', tres_pontos = '$new_value', tres_pontos_min = '$tres_pontos_min', tres_pontos_media = '$media_tres_pontos', media_todos = '$media_resultados_total', overall_check = '1' WHERE keyword = '$nomek' ";
mysql_query($sql);
	 //palavra_associada(1 palavra)
	 $sql = "UPDATE keywords SET keyword_associada= CONCAT('" . mysql_real_escape_string($palavradb) . "', ' ', keyword_associada) WHERE keyword = '$nomek' ";
mysql_query($sql);
			} else {//M3000 // se nao existir linha
			$tres_pontos = "00 00 $valor";
			$tres_pontos_media = $valor / 3;
		mysql_query("insert into keywords set keyword = '$nomek', data = '$hoje', pontuacao_maxima = '$valor', tres_pontos = '$tres_pontos', tres_pontos_min = '00', tres_pontos_media = '$tres_pontos_media', todos_resultados = '$valor', media_todos = '$valor', keyword_associada = '$palavradb', overall_check = '1'", $db);		
				} //F3000
	$contador++;
		}//F2000
	} else {//M1000 //mais do que uma palavra
		//formatos po defeito para gravar na bd atraves da condição >2 palavras e que não existe nenhum resultado ainda
		$tres_pontos = "00 00 00";
		//criar duas arrays, uma para pontos e outra com a respectiva palavra
		$keysrel_nomeinverte = $keysrel; //adquire a array 
		$keysrel_nomeinverte = array_keys($keysrel_nomeinverte); //inverte os valores
		$keysrel_numeracao = $keysrel;
		$keysrel_numeracao = array_filter(array_values($keysrel_numeracao), create_function('$item','global $nmin; return $item>=$nmin;'));
		//inicia o sistema para checar palavra a palavra
		$contador = 0;
		foreach ($keysrel_numeracao as $valor) { //5000 //por cada palavra autorizada faz o tratamento individual
		$nomek = $keysrel_nomeinverte[$contador];
		$existek_result = mysql_query("SELECT * FROM keywords where keyword = '$nomek'", $db);
		$existek_rows = mysql_num_rows($existek_result);
		$existek = mysql_fetch_object($existek_result);
			if($existek_rows == 1){ //6000  //se já existir uma linha
			//repeticao de chamadas
			$repete = $existek->keys_assoc_repete;
			$repete = $repete + 1;
			//pontuação de palavras - ?????????????ver update da bd
			//pontuação média
			$media = $existek->keys_assoc_pontos;
			if($media == ""){ //7000
			$media = $valor;
			} else { //M7000
			$arraymedia = explode(' ', $media);
			$resul = count($arraymedia);
			$resul = $resul + 1;
			$media = array_sum($arraymedia);
			$media = $media + $valor;
			$media = $media / $resul;
			}//F7000 
			//faz upgrade á bd e insere as palavras de busca actuais
			$conjunto = $palavradb;
			$conjunto = "$conjunto .";
			$sql = "UPDATE keywords SET keyword_associada_sec = CONCAT('" . mysql_real_escape_string($conjunto) . "', ' ', keyword_associada_sec), keys_assoc_pontos = CONCAT('" . mysql_real_escape_string($valor) . "', ' ', keys_assoc_pontos), keys_assoc_repete = '$repete', keys_assoc_pontos_media = '$media', overall_check = '1' WHERE keyword = '$nomek' ";
mysql_query($sql);
			} else {//M6000 //ainda não existe a palavra ????? ver formatos por defeito no inicio do condicionalismo
			$conjunto = $palavradb;
			$conjunto = "$conjunto .";
			mysql_query("insert into keywords set keyword = '$nomek', data = '$hoje', tres_pontos = '00 00 00', tres_pontos_min = '00', tres_pontos_media = '00', keyword_associada_sec = '$conjunto', keys_assoc_repete = '1', keys_assoc_pontos = '$valor', keys_assoc_pontos_media = '$valor', overall_check = '1'", $db);	
			}//F6000
			$contador++;	
		}//F5000
	}//F1000

Open in new window

0
 
Ray PaseurConnect With a Mentor Commented:
Hi, JC.  I am not sure I understand your issues using foreach or looking for a substring, but you have an error in your use of MySQL.  You are using mysql_query() without testing for success.  Here is the correct way to do that.  You should update your code to test the queries for success and to print diagnostic information on failure.
// CREATING A TABLE
$sql = " /* YOUR QUER STRING HERE */";
$res = mysql_query($sql);
 
// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}

Open in new window

0
 
Ray PaseurCommented:
Also, take note of the indenting used at the control structures in the code snippet above.  Note that the curly braces like { and } line up under each other.  This will make your code MUCH more readable.

Perhaps you can simplify your question.  If so, please post back here and I will try to help with a succinct answer.  But at this point, I think cxr showed you the basis of how to handle this challenge.

Best regards, ~Ray
0
 
Roger BaklundCommented:
>> I try to do this solution in my real code and don't work.

Your code does not contain any occurences of strpos(),  and I don't see where it was supposed to be used. Variable names and comments in a language I don't understand does not make it easier... could you please point me to the correct place in the source code?

>> So, how I interrupt the foreach when the system discover equal words?

In general, use the "continue;" keyword. This will stop the execution of the current loop and continue the foreach with the next item in the array.
0
 
Pedro ChagasWebmasterAuthor Commented:
Thanks @ray for yours posts!
@cxr, I'm sorry my bad english, I try to explain better then I can.

I try to put strpos example in lines 13 and 72, but the function don't work. Why don't work? because the system will just save in database the word that I want that not be save in database (is contrary to the desired).

I use strpos in this way:
if(strpos($nomek,$palavradb)!==false){ //line 13 and 72. $palavradb can contain a word or more then 2 words, and be check in each foreach and have allways the same value.
} //close the cycle of line 13 and 72 in lines 58 and 102.

Basecly what I want is, if the script found equal words between $nomek and $palavradb (like: batata - batata OR world - the great world), the foreach don't progresses for that value and will check the next value.

So, the problem now is why the script just save in db the word that I don't want, like:
If $palavradb = poker and $nomek was poker they save and read all script, but if $nomek = cards the system don't work. In this example the system should save cards and not poker.
This is the only problem when I use strpos.

Can help me with srtpos or other solution?

Regards, JC



 
0
 
Roger BaklundCommented:
I have inserted the strpos() condition the two places you described. I also fixed the indentation, it makes it easier to read. That is the only changes I have done in the snippet below.

>> the system should save cards and not poker.

Are you saying it is working the oppsite way of what you want? If so, just change the !== to === like this:

    if(strpos($nomek,$palavradb)===false){
if ($n_palavras_b == 1){//1000  //se for só uma palavra
  $nmin = 10; //grava a partir de 10 valores
  //adquire 2 arrays, uma com os nomes e outra com os pontos
  $keysrel_nomeinverte = $keysrel; //adquire a array 
  $keysrel_nomeinverte = array_keys($keysrel_nomeinverte); //inverte os valores
  $keysrel_numeracao = $keysrel;
  $keysrel_numeracao = array_filter(array_values($keysrel_numeracao), create_function('$item','global $nmin; return $item>=$nmin;'));
        
  //inicia o sistema para checar palavra a palavra
  $contador = 0;
  foreach ($keysrel_numeracao as $valor) { //2000 //por cada palavra autorizada faz o tratamento individual 
    $nomek = $keysrel_nomeinverte[$contador];
    if(strpos($nomek,$palavradb)!==false){
      $existek_result = mysql_query("SELECT * FROM keywords where keyword = '$nomek'", $db);
      $existek_rows = mysql_num_rows($existek_result);
      $existek = mysql_fetch_object($existek_result);
      //pontuacao maxima
      if($existek_rows == 1){ //3000  //se já existir uma linha
        $pontuacaodb = $existek->pontuacao_maxima;
        if($pontuacaodb < $valor){ //4000 //se o valor novo for mais alto do que lá está na bd
          $pontuacao_max = $valor;
        } else {
          $pontuacao_max = $pontuacaodb;
        } //F4000
        //tres_pontos
        $value = "$existek->tres_pontos";
        $numbers = explode(' ',$value);
        $new_number = $valor;
        if(strlen($new_number)<2)        # if less than two digits...
          $new_number = '0'.$new_number; # ...prefix with a 0 
        $numbers[] = $new_number;
        sort($numbers);
        while(count($numbers) > 3)  # if more than 3 numbers
          array_shift($numbers);    # remove smallest number
        $new_value = implode(' ',$numbers);
        echo "<br>NEW $new_value";
        //tres_pontos_min
        $tres_pontos_min = $numbers[0];
        //tres_pontos_media
        $media_tres_pontos = array_sum($numbers) / 3;
        //media todos_resultados
        $media_resultados = $existek->todos_resultados; //saca a string
        $media_resultados = explode(' ', $media_resultados); //converte em array
        array_push($media_resultados, "$valor"); //introduz uma nova key com o valor actual
        $n_chaves = count($media_resultados); //verifica quantas chaves existem
        $media_total = array_sum($media_resultados); //soma todos os valores da array
        $media_resultados_total = $media_total / $n_chaves; //arranja a media 
        //todos resultados
        $sql = "UPDATE keywords SET todos_resultados= CONCAT('" . mysql_real_escape_string($valor) . "', ' ', todos_resultados), pontuacao_maxima = '$pontuacao_max', tres_pontos = '$new_value', tres_pontos_min = '$tres_pontos_min', tres_pontos_media = '$media_tres_pontos', media_todos = '$media_resultados_total', overall_check = '1' WHERE keyword = '$nomek' ";
        mysql_query($sql);
        //palavra_associada(1 palavra)
        $sql = "UPDATE keywords SET keyword_associada= CONCAT('" . mysql_real_escape_string($palavradb) . "', ' ', keyword_associada) WHERE keyword = '$nomek' ";
        mysql_query($sql);
      } else {//M3000 // se nao existir linha
        $tres_pontos = "00 00 $valor";
        $tres_pontos_media = $valor / 3;
        mysql_query("insert into keywords set keyword = '$nomek', data = '$hoje', pontuacao_maxima = '$valor', tres_pontos = '$tres_pontos', tres_pontos_min = '00', tres_pontos_media = '$tres_pontos_media', todos_resultados = '$valor', media_todos = '$valor', keyword_associada = '$palavradb', overall_check = '1'", $db);               
      } //F3000
    }
    $contador++;
  }//F2000
} else {//M1000 //mais do que uma palavra
  //formatos po defeito para gravar na bd atraves da condição >2 palavras e que não existe nenhum resultado ainda
  $tres_pontos = "00 00 00";
  //criar duas arrays, uma para pontos e outra com a respectiva palavra
  $keysrel_nomeinverte = $keysrel; //adquire a array 
  $keysrel_nomeinverte = array_keys($keysrel_nomeinverte); //inverte os valores
  $keysrel_numeracao = $keysrel;
  $keysrel_numeracao = array_filter(array_values($keysrel_numeracao), create_function('$item','global $nmin; return $item>=$nmin;'));
  //inicia o sistema para checar palavra a palavra
  $contador = 0;
  foreach ($keysrel_numeracao as $valor) { //5000 //por cada palavra autorizada faz o tratamento individual
    $nomek = $keysrel_nomeinverte[$contador];
    if(strpos($nomek,$palavradb)!==false){
      $existek_result = mysql_query("SELECT * FROM keywords where keyword = '$nomek'", $db);
      $existek_rows = mysql_num_rows($existek_result);
      $existek = mysql_fetch_object($existek_result);
      if($existek_rows == 1){ //6000  //se já existir uma linha
        //repeticao de chamadas
        $repete = $existek->keys_assoc_repete;
        $repete = $repete + 1;
        //pontuação de palavras - ?????????????ver update da bd
        //pontuação média
        $media = $existek->keys_assoc_pontos;
        if($media == ""){ //7000
          $media = $valor;
        } else { //M7000
          $arraymedia = explode(' ', $media);
          $resul = count($arraymedia);
          $resul = $resul + 1;
          $media = array_sum($arraymedia);
          $media = $media + $valor;
          $media = $media / $resul;
        }//F7000 
        //faz upgrade á bd e insere as palavras de busca actuais
        $conjunto = $palavradb;
        $conjunto = "$conjunto .";
        $sql = "UPDATE keywords SET keyword_associada_sec = CONCAT('" . mysql_real_escape_string($conjunto) . "', ' ', keyword_associada_sec), keys_assoc_pontos = CONCAT('" . mysql_real_escape_string($valor) . "', ' ', keys_assoc_pontos), keys_assoc_repete = '$repete', keys_assoc_pontos_media = '$media', overall_check = '1' WHERE keyword = '$nomek' ";
        mysql_query($sql);
      } else {//M6000 //ainda não existe a palavra ????? ver formatos por defeito no inicio do condicionalismo
        $conjunto = $palavradb;
        $conjunto = "$conjunto .";
        mysql_query("insert into keywords set keyword = '$nomek', data = '$hoje', tres_pontos = '00 00 00', tres_pontos_min = '00', tres_pontos_media = '00', keyword_associada_sec = '$conjunto', keys_assoc_repete = '1', keys_assoc_pontos = '$valor', keys_assoc_pontos_media = '$valor', overall_check = '1'", $db);       
      }//F6000
    }
    $contador++;    
  }//F5000
}//F1000

Open in new window

0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @cxr, continues don't work, including change to === false.
I want to know where is the error, so I put more this two lines to view the contain of variables:
$lif = strpos($nomek,$palavradb); //line 14
echo "<br>$lif ---- $nomek ---- $palavradb<br>"; //line 15
If I use '!==false', the script save in database the word that I don't want to save, and give me this output (consider $palavradb = bolacha):
0 ---- bolacha ---- bolacha

If i use '===false' the system don't save anything.

If I erase the line 13 and 59, and continue with this lines:
$lif = strpos($nomek,$palavradb);
echo "<br>$lif ---- $nomek ---- $palavradb<br>";
and consider $palavradb = paixao, the output is:
0 ---- paixao ---- paixao
---- dia ---- paixao
---- bodas ---- paixao
---- genero ---- paixao
---- amor ---- paixao
---- musical ---- paixao

So, maybe the problem was the boolean. I don't know, but is very strange. Maybe what you talk some posts ago about apostrophes or quotes are influence in this case.

Regards, JC
0
 
Roger BaklundCommented:
>> continues don't work

In this case you have this structure:

foreach(...) {
  # some code
  if(...) {
     # save to database
  }
}

If you were to use "continue;", you would use it like this:

foreach(...) {
  # some code
  if(...) continue;
  # save to database
}

Note that one set of {} is removed.

>> If i use '===false' the system don't save anything.

That was odd. It should save those words that was NOT saved when you used '!==false'. "===" is the opposite of "!==", the ! means "not".

>> and consider $palavradb = paixao, the output is:
>> 0 ---- paixao ---- paixao
>> ---- dia ---- paixao

For the first word, "paixao", the value of $lif is 0, and it is !==false. For the second word, "dia", the value of $lif is false (which makes no output, it won't print 'false') and it should be saved if you used ===false.

When you are comparing single words, you should not use strpos(), you should use just: if($nomek!=$palavradb). It is slightly faster, and it makes the code easier to understand. Never use more complicated code than what is needed.
0
 
Pedro ChagasWebmasterAuthor Commented:
<<When you are comparing single words, you should not use strpos(), you should use just: if($nomek!=$palavradb). It is slightly faster, and it makes the code easier to understand. Never use more complicated code than what is needed.>>
Maybe was the solution for singles words, and if it is for more then 1 word?

Regards, JC
0
 
Ray PaseurCommented:
If you use explode() to make the array of words, be sure to do two things.  First, change all whitespace to single spaces so you don't get tripped up by a tab or newline character.  Second, consider using array_unique() to reduce the amount of storage needed for the array of words.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.