简体   繁体   中英

Check if variable exist in specific array key (PHP, MYSQLI)

EDIT: SOLVED - works as expected. Issue was with $search variable. Thanks for all of your help.

I have a typical WHILE that looks like this:

while ($row = $result->fetch_assoc())

In my $row, I have a user_name key that looks like $row["user_name"].

I have a variable called $search.

Theoretically, $search could be in another key in the $row array, for example is could also be in $row["user_id"].

I'm trying to use stripos to see if there's a non-case-sensitive instance where $search is "like", or in the key, $row["user_name"].

I've even tried storing $row["user_name"] in a separate variable.

Basically.

if(stripos($row["user_id"],$search) !== false){
echo("working");
}

This never happens. Please help!

Edit: Let me rephrase.

All I need to do is see if the $row["user_name"] CONTAINS what's in the string variable $search.

I've tried to convert $row["user_name"] into an array, a string, etc and tried in_array and stripos and nothing works.

The below will work:

if (stripos("hey you guys","guys")){
    echo("worked");
    }

But what I need is

if (stripos($row["user_name"],$search)){
    echo("worked");
    }

Edit: var_dump looks like array(2) { ["user_id"]=> string(3) "133" ["user_name"]=> string(3) "mrp" }

Edit: I already verified that both $row["user_name"] and $search are strings so I don't get the issue.

<?php
    $search = 'bar';
    $row = array('id' => 'fOo', 'name' => 'BAr', 'troll' => 'zer');

    // Method 1: preg_match
    $ret = (bool)preg_match('`(' . implode('|', array_values($row)) . ')`i', $search);

    // Method 2: array_search
    $ret = array_search(strtolower($search), array_map('strtolower', $row)) !== false;

    if ($ret) {
      echo 'found';
    } else {
      echo 'not found';
    }
?>

When you use fetch_assoc , it returns not an array, but an object. So try different syntax:

stripos($row->user_id, $search) 
$string = str_replace($search,"",$row['user_id']);
$ctr = count($string);
   if($ctr>0) {echo 'found!';}
   else {echo 'not found!';}

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