PHP array always returns false with Codeigniter Framework

advertisements

I have this code in my Authentication.php (Controller)

public function check_user_name(){
    $userName = $this->input->post('UserName');

    $people = array();
    $people[] = array('UserName' => 'Junjun');
    $people[] = array('UserName' => 'Kent');

    if (in_array($userName, $people))
      {
        $result = array('result' => true);
      }
    else
      {
        $result = array('result' => false);
      }

    echo json_encode($result);
}

and i got my ajax code

 $(document).ready(function() {

/*/
 * Declarations
/*/
var host = 'http://' + window.location.host + '<?php echo $this->config->item('base_folder'); ?>';
var txtUserName = $('#text-user-name');
var txtPassword = $('#text-password');
var btnNext = $('#button-next');
var btnLogin = $('#button-login');
var grpUserName = $('#group-username');
var grpPassword = $('#group-password');

/*/
 * Bindings
/*/
btnNext.on('click', btnNext_Click);

/*/
 * Events
/*/
function btnNext_Click() {
  event.preventDefault();
  //grpUserName.addClass('hidden');
  grpUserName.find('h1').text('Checking....');

  var post_data = new FormData();

  post_data.append('UserName', txtUserName.val());

  $.ajax({
    url: 'http://localhost/pms/authentication/check_user_name',
    type: 'POST',
    dataType: 'json',
    contentType: false,
    processData: false,
    data: post_data, //post_data,
    success: function(data) { console.log(data);
      if(data.result == true){
        grpPassword.removeClass('hidden');
        grpUserName.addClass('hidden');
      }
      else{
        grpUserName.find('h1').text('Invalid User Name!');
      }
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}
});

the problem in the console is it always returns false, what is wrong with my associative array? help please!


This bit is wrong

$people = array();
$people[] = array('UserName' => 'Junjun');
$people[] = array('UserName' => 'Kent');

It will give you an array like this ( multi dimension )

$people = [
    ['UserName' => 'Junjun'],
    ['UserName' => 'Kent']
];

so in_array fails to find the key you are looking for.

 if (in_array("Junjun",[
    0 => ['UserName' => 'Junjun'],
    1 => ['UserName' => 'Kent']
])){ ... }

See "Junjun" is not equal to either of those 2 sub-arrays. Instead just add them:

   $people = array();
   $people[] = 'Junjun';
   $people[] = 'UserName';

   //or
   $people = array('Junjun','UserName');

So your array looks like this

   $people = ['Junjun','Kent'];