Search code examples
phparrayssessionstrpos

Match a string in an array strpos(): Empty needle


I have a string from database that I want to match with an array but it results in error saying:

strpos(): Empty needle in line X

if (!isset($_SESSION['arry'])) {
    $_SESSION['arry'] = array();
}
$imp = 42;
$arrys =  $_SESSION['arry'];

foreach($arrys as $string)
{
  if(strpos($imp, $string) !== false) 
  {
    $pow =1;
    break;
  }
}

if($pow==1){ exit; }

The array looks like this:

Array
(
    [0] => 218
    [1] => 219
    [2] =>  218
    [3] => 220
    [4] => 222
    [5] =>  42
    [6] => 223
)

Solution

  • You are doing the opposite way , searching string in 42 , instead go for

    strpos($string, $imp)
    

    TRY THIS : (updated)

    <?php
    
        $_SESSION['arry'] = array(236,235,239,243,246);
    
    $imp =  239;
    $arrys =  $_SESSION['arry'];
    $arrys = array_unique($arrys);
    $pow = "";
    print "<pre>";
    print_r($arrys);
    print "</pre>";
    foreach($arrys as $string)
    {
    if($string == $imp)  {
        $pow = 1; echo "we have".$imp."in array<br/>";
    }
    else{
        $pow = 0; echo "sorry".$imp."wasn't found in array<br/>";
    }
    }
    ?>