I have a php function.
if ( $this->input->post('email') == $this->_email($this->input->post('email')) )
{
$this->_data['error'] = 'Email exist!';
return $this->load->view('login/template_view', $this->_data);
}
My function returning only FALSE, even if equality is true. I use debug to see if my function can returning TRUE.
bool(false) string(14) "alex#yahoo.com" object(stdClass)#25 (1) { ["email"]=> string(14) "alex#yahoo.com" }
I have 2 strings, first is returning alex#yahoo.com, and 2nd string is returning alex#yahoo.com... but if condition still returning FALSE.
What is wrong in my function?
Debug:
var_dump($this->input->post('email'));
var_dump($this->_email($this->input->post('email')));
die();
You are comparing a string to an object. In order for your comparison to work, you need to compare the string against the email property of the object. You can access a object property by using -> or by using a method.
You can read more about PHP objects here and here.
In order for your code to work, replace:
if ( $this->input->post('email') == $this->_email($this->input->post('email')) )
with
if ( $this->input->post('email') == $this->_email($this->input->post('email'))->email )
Related
I have a boolean field that is represented by 0 and 1 in my database.
if ($request->input('submitted')) {
// do code
}
This has been working because it's only been setting the field to 1 (true) but now there's a new flow that can revert the submission.
It has not been setting it back to 0 when I pass the value 0 in from the frontend and I assume it's because that condition is getting skipped since 0 would eval to null.
Is the best way to handle it:
if (isset($request->input('submitted'))) {
// do code
}
or would strictly checking against null work better:
if ($request->input('submitted') !== null) {
// do code
}
The simply approach parse your input to a boolean.
if ((bool) $request->input('submitted')) {
This will create the following results. Therefor removing your edge case.
(bool) "1" // true
(bool) "1" // false
An alternative approach is to use inbuilt PHP filter, it will parse a lot of cases more notably "true" and "false" to true and false.
if (filter_var($request->input('submitted'), FILTER_VALIDATE_BOOLEAN)) {
I have an array inside the $_POST variable and i want to validate it:
$this->validator->set_rules('questions[]', 'questions', 'required|min_length[10]');
In this case i want the array questions to have length at least 10, the problem is that this doesn't work, for arrays with length < 10 the validator detects no error, here is my dumped post example:
array(1) { ["questions"]=> array(0) {} }
when i run:
if($this->validator->run() == false){...}else{...}
the method return true and the code will enter in the else.
Do someone knows how can i do this?
You can write a callback function, I am giving an example.
Suppose you want to limit your array for minimum 10 values.
$this->validator->set_rules('questions[]', 'questions', required|callback_checkLength');
And write the function like this :
function checkLength(){
if(count($this->input->post("questions[]") < 10) { return false };
else { return true; }
}
Hope this helps you.
In the PHP documentation for json_decode it says it can return TRUE,FALSE,NULL.
Could some help me understand when it would return FALSE? I understand invalid JSON will return NULL, but when would the other two be returned if not the actual JSON value?
Thanks
JSON format definition clearly shows all possible values and their representations:
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array.
Both objects and arrays have special syntax in JSON representation (wrapped in {} and [] respectively), so they can't be mixed up with false in any case. The same goes with string - it's wrapped in "" (double quotation marks). As for Numbers, they have to contain at least one digit - so cannot be confused with false (and true and null) too.
So that leaves us with the only case: when json_encode processes an object having redefined its JSON representation. For example (PHP 5.4+):
class FalsyFoo implements JsonSerializable {
public $foo;
public function __construct($f) {
$this->foo = $f;
}
public function jsonSerialize() {
return false;
}
}
$f = new FalsyFoo(true);
$fj = json_encode($f);
var_dump( $fj ); // string(5) 'false'
var_dump( json_decode($fj) ); // bool(false)
Technically, we still work with false value here, but the source is obviously different.
If you're still not convinced, check the source code of json_decode, which calls php_json_decode_ex after checking the arguments. This, in turn, calls parse_JSON_ex first, which operates over the predefined state transition table; the latter has only one set of states leading to false value as result. If this call fails somehow, value is checked directly:
if (str_len == 4) {
if (!strcasecmp(str, "null")) {
/* We need to explicitly clear the error
because its an actual NULL and not an error */
jp->error_code = PHP_JSON_ERROR_NONE;
RETVAL_NULL();
} else if (!strcasecmp(str, "true")) {
RETVAL_BOOL(1);
}
} else if (str_len == 5 && !strcasecmp(str, "false")) {
RETVAL_BOOL(0);
}
... and that's the only case when return_value is set to boolean.
The documentation says that values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. This means that if the booleans true orfalse are in the object to be encoded, they will be shows as TRUE or FALSE, and the same for null. For example:
json_decode('["hello",true]');
would return:
["hello",TRUE]
It doesn't mean that json_decode will return values of true, false, or null
I have an object as this:
object(stdClass)#27 (1)
{
[0] => object(stdClass)#26 (6)
{
["_id"] => object(MongoId)#24 (1)
{
["$id"] => string(24) "4e6ea439caa47c2c0c000000"
}
["username"] => string(16) "wdfkewkghbrjkghb"
["email"]=> string(24) "wdhbfjkwhegerg#€rg.efg"
["password"]=> string(32) "4297f44b13955235245b2497399d7a93"
["slug"]=> string(16) "wdfkewkghbrjkghb"
["insert_datetime"]=> string(19) "2011-09-13 12:09:49"
}
}
I assign this object to $user.
I can't get access on this object properties doing $user->username cause I receive the message:
Undefined property: stdClass::$username
Then if I do var_dump(get_object_vars($user)) it returns an empty array.
How do I grab the properties? I don't want to use loops if I can avoid it.
The process is this:
Retrieve results from mongo_db:
$returns = array();
while ($documents->hasNext())
{
if ($this->CI->config->item('mongo_return') == 'object')
{
$returns[] = (object) $documents->getNext();
}
if ($this->CI->config->item('mongo_return') == 'array')
{
$returns[] = (array) $documents->getNext();
}
}
if ($this->CI->config->item('mongo_return') == 'object')
{
return (object)$returns;
}
if ($this->CI->config->item('mongo_return') == 'array')
{
return $returns;
}
passing data to model
function populateBy($what = false) {
return $this->mongo_db
->where($what)
->get($this->tb['users']);
}
definitely grab results in controller:
$what = array(
'email'=>$email,
'password'=>$password,
'confirm'=>'1'
);
$user = $this->model_user->populateBy($what);
As gilden says, the property you're looking for is a property of a subobject. However, he missed that object property access is not the same as array element access.
The real problem you're facing here is that you've converted an array to object, and now you have a numeric property name. To get to properties you have to use syntax like $user->0->username, but clearly this is not valid as 0 is not a valid variable name.
From the documentation:
If an object is converted to an array, the result is an array whose
elements are the object's properties. The keys are the member variable
names, with a few notable exceptions: integer properties are
unaccessible [sic]; private variables have the class name prepended to the
variable name; protected variables have a '*' prepended to the
variable name. These prepended values have null bytes on either side.
This can result in some unexpected behaviour:
The function get_object_vars converts back into an array again so that it appears to work, but in fact anything could happen: the behaviour is unspecified because the object elements were rendered inaccessible in the intermediate stage. Similarly, $user->{'0'}->username may work for you but I would avoid it.
Unfortunately this means that you'll have to change the way your code works: do not convert a numerically-indexed array to an object.
Your username property is not where you're looking for it. Try
$username = $user[0]->username;
EDIT Trying this gives me some unexpected results. I get "Cannot use object of type stdClass as array" so what I think you should do is using a foreach loop
// $users is the object in this sample
foreach($users as $user)
{
$username = $user->username;
}
EDIT 2 You could use get_object_vars
$users = get_object_vars($users);
$username = $users[0]->username;
Using PHP 5.3 I'm experiencing weird / non-intuitive behavior when applying empty() to dynamic object properties fetched via the __get() overload function. Consider the following code snippet:
<?php
class Test {
protected $_data= array(
'id'=> 23,
'name'=> 'my string'
);
function __get($k) {
return $this->_data[$k];
}
}
$test= new Test();
var_dump("Accessing directly:");
var_dump($test->name);
var_dump($test->id);
var_dump(empty($test->name));
var_dump(empty($test->id));
var_dump("Accessing after variable assignment:");
$name= $test->name;
$id= $test->id;
var_dump($name);
var_dump($id);
var_dump(empty($name));
var_dump(empty($id));
?>
The output of this function is as follow. Compare the results of the empty() checks on the first and second result sets:
Set #1, unexpected result:
string(19) "Accessing directly:"
string(9) "my string"
int(23)
bool(true)
bool(true)
Expecting Set #1 to return the same as Set #2:
string(36) "Accessing after variable assignment:"
string(9) "my string"
int(23)
bool(false)
bool(false)
This is really baffling and non-intuitive. The object properties output non-empty strings but empty() considers them to be empty strings. What's going on here?
Based on a reading of the empty's manual page and comments (Ctrl-F for isset and/or double underscores), it looks like this is known behavior, and if you want your __set and __get methods and empty to play nice together, there's an implicit assumption that you implement a __isset magic method as well.
It is a little bit unintuitive and confusing, but that tends to happen with most meta-programming, particularly in a system like PHP.
In this example, empty() calls the __isset() overload function, not the __get() overload function. Try this:
class Test {
protected $_data= array(
'id'=> 23,
'name'=> 'my string'
);
function __get($k) {
return $this->_data[$k];
}
function __isset($k) {
return isset($this->_data[$k]);
}
}