简体   繁体   中英

How to search string for value using array in PHP?

Hi! I want to search string having value like "CMS" in array $row, below code is searching for exact "CMS".

if (mysql_num_rows($sql_result)>0)
  { 
    while ($row = mysql_fetch_assoc($sql_result))
        { $counter++; 
           if (in_array("CMS", $row)) 
               { $cms++; }
          }
    }

I'll be grateful if any one can guide me to how to search string for value LIKE "CMS" in array $row.

Use strpos and serialize

if (mysql_num_rows($sql_result)>0)
  { 
    while ($row = mysql_fetch_assoc($sql_result))
        { $counter++; 
           if (strpos(serialize($row),"CMS")!==false)  //<--- Changed this `if` statement, nothing else
               { $cms++; }
          }
    }

You could serialize your array and then do a strpos to check whether the needle is inside the array or not. This is something similar like doing a LIKE as you requested.

Loop over each of the columns in the row and use strpos

if (mysql_num_rows($sql_result)>0) 
{ 
    while ($row = mysql_fetch_assoc($sql_result))
    { 
        $counter++; 
        foreach($row as $column)
        {
            if (strpos($column, 'CMS'))
            {
                $cms++;
            }
        }
    }
}
if (mysql_num_rows($sql_result)>0)
  { 
    while ($row = mysql_fetch_assoc($sql_result))
        { $counter++; 
           foreach ($row as $column) {
              if (strpos($column, "CMS") !== false) {
                  $cms++;
              }
           } 

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM