Search code examples
phpframeworkscodeigniter-2

How to use function in_array with CodeIgneter


I am trying to use the PHP function in_array within a view using CodeIgneter.

This is the method

class User_details extends CI_Model {

public function checkID(){
$query = $this->db->query("SELECT id FROM users");

return $query->result_array();

}

This is the controller

$this->load->model('user_details');

$data['allUserID'] = $this->user_details->checkID();
$this->load->view('user_details/content',$data);

This is the script I am trying to use in the view

$id = $this->uri->segment(4);//user's id for example: 218


if(in_array($id,$allUserID)){
echo 'exists';
} else {
echo 'does not exist';
}

Unfortunately he script does not work as expected.

If I check the array using print_r($allUserID) I get following result:

Array ( [0] => Array ( [id] => 217 ) [1] => Array ( [id] => 218 ...
...and so on...

Last week I started learning CodeIgneter and I did not understand its approach yet.


Solution

  • in_array() accept single dimensional array and you are passing two dimensional array. Try converting it to single dimensional array like

    $array = array_map('current', $allUserID);
    
    if(in_array($id, $array)){
     echo 'exists';
    } else {
      echo 'does not exist';
    }