1

I am having a hard time with this. Although am new here. I am using Codeigniter, This is the query code.

<?php
    $is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'");
    $check = $is_member->result_array();
    if (in_array($id, $check)) {
        echo "Match found";
    } else {
        echo "Match not found";
    }
?>

Which outputs Match not found

but print_r($check) gives

Array ( [0] => Array ( [user] => 1 ) [1] => Array ( [user] => 2 )

So how am I going to check if a specific integer is in the array which is multidimensional I think.

Note: $id = 1, which is clearly in the array, but it still saying not found. Any answers? feel free to correct me if am doing something wrong

3
  • do you only need to use in_array for "user" ? Commented Feb 13, 2020 at 13:41
  • what's in $id? Commented Feb 13, 2020 at 14:00
  • @Chemaclass its an integer 1 Commented Feb 13, 2020 at 19:54

2 Answers 2

1

I think the best way to do it is having a foreach loop, in_array wouldn't work on the root array.

<?php
$is_member = $this->db->query("SELECT user FROM chatroom_members WHERE room='$row->id'");
$arrays = $is_member->result_array();

$found = false;
foreach ($arrays as $array) {
   if(in_array($id,$array)) {
     $found = true; 
     break;
   }
} 
echo $found === true ? "Match found" : "Match not found";
?>
Sign up to request clarification or add additional context in comments.

Comments

0

If you already know the ID you're looking for and the room ID where you want to check, you might benefit from doing this:

(I'm assuming here that the room number is contained in $row->id and the user ID you're looking for is $id)

$this->db->select('user');
$this->db->from('chatroom_members');
$this->db->where('room', $row->id);
$this->db->where('user', $id);

$query = $this->db->get();
return ($query->num_rows() == 0) ? false : true;

You'll save yourself from looping through a huge result array (which may or may not be an issue depending on how large the resultset from the table is) and you'll get a simple yes/no answer. I used a return and a ternary operator but you can easily change that to an if/else and do something else than return true or false depending on what you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.