Question

Cycle with foreach (interrupt)

Asked by: joaochagas

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

                                  
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-03 at 09:37:56ID24542690
Tags

php

,

foreach

,

array

,

interrupt

Topic

PHP Scripting Language

Participating Experts
2
Points
500
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

    Free Tech Articles

    1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
      It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
    2. SCCM OSD Basic troubleshooting
      SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
    3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
      This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
    4. Create a Win7 Gadget
      This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
    5. Outlook continually prompting for username and password
      There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
    6. Backup Exchange 2010 Information Store using Windows Backup
      There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

    Cloud Class Webinars

    1. Avoiding Bugs in Microsoft Access
      Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
    2. Top 10 Best New Features in Visio 2010
      Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
    3. IT Consultant Business Secrets Revealed
      Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
    4. Disaster Recovery and Business Continuity
      Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
    5. Organize Your Visio Diagrams with Containers and Lists
      Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
    6. How to Us Objects, Properties, Events and Methods in Microsoft Access
      Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

    Join the Community

    Give a Little. Get a Lot.

    Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

    Join the Community

    Answers

     

    by: cxrPosted on 2009-07-03 at 09:49:13ID: 24773408

    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";
    }
    
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    

    Select allOpen in new window

     

    by: joaochagasPosted on 2009-07-03 at 10:38:33ID: 24773639

    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

     

    by: cxrPosted on 2009-07-03 at 10:46:43ID: 24773669

    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

     

    by: cxrPosted on 2009-07-03 at 10:47:34ID: 24773671

    Sorry, I wrote substr when I meant strpos...

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

     

    by: joaochagasPosted on 2009-07-03 at 17:06:58ID: 24775007

    Hi @cxr, why '!==false'? Why you don't use '==true'?

    Regards, JC

     

    by: cxrPosted on 2009-07-03 at 17:38:32ID: 24775079

    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.

     

    by: joaochagasPosted on 2009-07-04 at 04:56:47ID: 24776689

    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
    
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    8:
    9:
    10:
    11:
    12:
    13:
    14:
    15:
    16:
    17:
    18:
    19:
    20:
    21:
    22:
    23:
    24:
    25:
    26:
    27:
    28:
    29:
    30:
    31:
    32:
    33:
    34:
    35:
    36:
    37:
    38:
    39:
    40:
    41:
    42:
    43:
    44:
    45:
    46:
    47:
    48:
    49:
    50:
    51:
    52:
    53:
    54:
    55:
    56:
    57:
    58:
    59:
    60:
    61:
    62:
    63:
    64:
    65:
    66:
    67:
    68:
    69:
    70:
    71:
    72:
    73:
    74:
    75:
    76:
    77:
    78:
    79:
    80:
    81:
    82:
    83:
    84:
    85:
    86:
    87:
    88:
    89:
    90:
    91:
    92:
    93:
    94:
    95:
    96:
    97:
    98:
    99:
    100:
    101:
    102:
    103:
    104:
    

    Select allOpen in new window

     

    by: Ray_PaseurPosted on 2009-07-04 at 14:53:28ID: 24778135

    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);
    }
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    8:
    9:
    10:
    11:
    12:
    

    Select allOpen in new window

     

    by: Ray_PaseurPosted on 2009-07-04 at 14:58:07ID: 24778146

    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

     

    by: cxrPosted on 2009-07-04 at 15:36:47ID: 24778229

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

     

    by: joaochagasPosted on 2009-07-04 at 19:04:45ID: 24778593

    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



     

    by: cxrPosted on 2009-07-04 at 19:17:46ID: 24778630

    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
    
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    8:
    9:
    10:
    11:
    12:
    13:
    14:
    15:
    16:
    17:
    18:
    19:
    20:
    21:
    22:
    23:
    24:
    25:
    26:
    27:
    28:
    29:
    30:
    31:
    32:
    33:
    34:
    35:
    36:
    37:
    38:
    39:
    40:
    41:
    42:
    43:
    44:
    45:
    46:
    47:
    48:
    49:
    50:
    51:
    52:
    53:
    54:
    55:
    56:
    57:
    58:
    59:
    60:
    61:
    62:
    63:
    64:
    65:
    66:
    67:
    68:
    69:
    70:
    71:
    72:
    73:
    74:
    75:
    76:
    77:
    78:
    79:
    80:
    81:
    82:
    83:
    84:
    85:
    86:
    87:
    88:
    89:
    90:
    91:
    92:
    93:
    94:
    95:
    96:
    97:
    98:
    99:
    100:
    101:
    102:
    103:
    104:
    105:
    106:
    107:
    108:
    

    Select allOpen in new window

     

    by: joaochagasPosted on 2009-07-05 at 10:38:56ID: 24780665

    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

     

    by: cxrPosted on 2009-07-05 at 11:46:52ID: 24780882

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

     

    by: joaochagasPosted on 2009-07-05 at 11:54:08ID: 24780913

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

     

    by: cxrPosted on 2009-07-05 at 12:24:59ID: 24781015

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

     

    by: Ray_PaseurPosted on 2009-07-05 at 12:33:02ID: 24781046

    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.

    20120131-EE-VQP-002

    3 Ways to Join

    30-Day Free Trial

    The Experts

    98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

    He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

    The Experts

    97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

    The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

    Testimonials

    "...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

    Testimonials

    "I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

    Testimonials

    "WOW! You guys have great, active, and knowledgeable people on here." moore50

    Business Clients

    Business Clients

    In the Press

    "If you’ve got a question... Experts Exchange can supply an answer.”

    In the Press

    "...an invaluable aid for both IT professionals and those who require tech support."

    In the Press

    "where IT professionals provide quick answers on just about any topic"

    Business Account Plans

    Loading Advertisement...