Nishant Jani
Nishant Jani

Reputation: 1993

in_array() codeginter PHP

hello members a anomaly in codeigniter im noticing

in my model im querying the database to get a list of user_id ONLY

$recs = $this->db->query('select id from users');

that was easy, but i want to return the result as an array

so i do

$reccs->result_array();

but now in my controller i want to check for in_array(124,$returned_array); this is not successful because codeigniter has encapsulated the array of id into a v big outer array something like this

Array ( [0] => Array ( [id] => 0 ) [1] => Array ( [id] => 11 )           [2]  =>   Array ( [id] => 29 )) 

how can i use the in_array php function to check only id ?

OR

how can i built a plain array just to store id something like

 $demo = array();
 foreach($recs as $r)
 $demo = array($r->id);

Any suggestions ?

Upvotes: 1

Views: 4595

Answers (4)

user1594523
user1594523

Reputation: 26

You can loop the result set and generate a ne w array and make use of it. Below is the code which may be usefull

$i=0;
foreach($reccs->result_array() as $values)
{
$new_array[]=$values[$i]['id'];
$i++;
}

make use of $new_array for in_array comparision

Upvotes: 1

Telémako
Telémako

Reputation: 673

As the other comments are saying, there are better ways to do this but as you insist to do it like this, just transform the id into an array to match the result array structure:

in_array(array('id' => 124),$returned_array)

Upvotes: 1

Loken Makwana
Loken Makwana

Reputation: 3848

If you want to check whether user is there or not you should make a count query.

$this->db->where('id',124);
$count = $this->db->count_all_results('users');

if($count) {
// found
} else {
// not found
}

Upvotes: 2

alex
alex

Reputation: 490461

You could use array_map() to pluck that key from each sub array. Then, in_array() will work as per normal.

$found = in_array(124, 
                  array_map(function($val) { return $val['id']; },
                            $returned_array
                  )
         );

If you don't have >= PHP 5.3, then replace the anonymous function with a named one.

Upvotes: 0

Related Questions