syntax explanation, please?
I'm making a tiny application, and I'm using post-data. And the PHP 5.3 throws warnings if i don't check if a $_POST variable is set before trying eg. $var = $_POST['somevariable'];
And what I wanted to do is making as small code as possible, but still check if the post-var is set or not, and if one of the post-vars is not set, it should set a $error variable to true.
So I wrote the code like this.
What happens is that, if $_POST['userid'] is set then $userid should get it's value. But if its not, $userid should get the value 43, and the $error variable should be set to true. And it sure works. But I don't really get what happens there. I just tried the $error = true | 43 by a coincidence, and it works, but I'm not sure if it's really the right way of doing it? Is this really correct syntax?
$error = false;
$userid = isset($_POST['userid']) ? $_POST['userid'] : $error = true | 43;
if($error == true) echo "error\n";
And if it is good syntax... Is it any way of making this even shorter? for example so I don't have to write $_POST['userid'] two times? So I could replace it with $1 or something like that.
The single pipe "|" is the bitwise "or" operator. So true is cast to an integer 1 ("1" in binary), while 43 in binary is "101011". So when those two values are used with the "|" operator, "Bits that are set in either $a or $b are set." (See PHP Bitwise Operators), the result is still binary "101011" which is 43. If you instead use 42 for the "default", you would find that $userid is still set to 43 because of that ones digit being set by the "true".
Oh, and the if is evaluating to true because you use the "==" comparison operator, which allows type-casting, so the 43 is considered "true" since it is non-zero. If you used the "===" is-identical-to operator, then it would fail since integer 43 is not the same type/value as a boolean true.
okay. So what the code is really saying is:
"set $userid to $_POST['userid'], if $_POST['userid'] is set, else set $userid to (if $error can be set to true) combined with 43 bitwise"
so 1 | 43 is bitwise 1 combined with 101011 which is 101011
and if I would put 42 it'd be 101010 combined with 1 which is also 101011
Is this the correct way to interpret it?
Yes, I think you understood it.
Originally Posted by artheus
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread