Home » Php » php – How can i check if a value is in codeigniter result_array()

php – How can i check if a value is in codeigniter result_array()

Posted by: admin February 25, 2020 Leave a comment

Questions:

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

How to&Answers:

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.

Answer:

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";
?>