Good afternoon guys. There is an array, let's call it UserArticleList , here is its vardamp:

 array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } 

There is such a piece of code:

 foreach($ArticleList as $article){ if(array_search($article['id'],$UserArticleList)){ continue; //Продолжаем обрабатывать запись } 

Here the loop $ArticleListas all the records in the $ArticleListas ( $ArticleListas ). If the id current record is in the array, then go to the next iteration of the loop. And everything should work, but array_search finds only an element with a value of 2 . Why?)

  • in a loop, do tcho $ article ['id'] .... what does it output? exactly different IDs from the database? - Arsen
  • @Arsen, I'll try now - Alexey Vladimirovich
  • @Arsen displays 2, yes, id is different, there are 2 records, I’m wardampil, they have id = 1 and 2) - Alexey Vladimirovich
  • @Arsen, and if you print id before checking for the presence of that in the array, it displays both the first and second (1, 2). With Id, everything is normal. - Alexey Vladimirovich
  • one
    so you are looking for a key or value ?? - Arsen

3 answers 3

The docks say that:

Warning This function can return both a boolean FALSE and a non-boolean value, which is converted to FALSE. For more information, see the Boolean type. Use the === operator to check the value returned by this function.

Accordingly, when the first element is encountered, the key number 0 is returned. And in view of the implicit conversion of 0 to the boolean type, we get a structure like this:

 if (false) { .... 

so he finds nothing.

Consequently. It is necessary to write either like this:

 if(array_search($article['id'],$UserArticleList) !== false){... 

or use in_array :

 if(in_array($article['id'],$UserArticleList)){... 
     foreach($ArticleList as $article){ if(in_array($article['id'],$UserArticleList)){ do some... } } 

    If you also want to compare types, add true:

     in_array($article['id'],$UserArticleList,true) 
    • Thanks, it helped) - Alexey Vladimirovich
    • Always please;) - Kirill Korushkin

    And what's stopping you from using in_array ?

     <?php foreach($ArticleList as $article){ if(in_array($article['id'],$UserArticleList)){ continue; //Продолжаем обрабатывать запись } ?>