php wont check the second argument even if the first is true - php

I wrote this:
$a[] = "guy";
$b[] = "g";
function login($a1, $b1)
{
if( user($a1) == true and pass1($b1) == true)
{
login2($a1, $b1);
}
else
{
echo "error!!!!";
}
}
function login2($a1, $b1)
{
if (array_search($_REQUEST["user"],$a1) == array_search($_REQUEST["pass"],$b1))
{
echo "you are logged in";
}
else
{
echo "erorr";
}
}
function user($user1)
{
if(in_array($_REQUEST["user"],$user1))
{
echo "gooooooood?";
}
}
function pass1($pas)
{
if(in_array($_REQUEST["pass"],$pas))
{
echo "goooooooood!!!!!!!!";
}
else
{
echo "bad";
}
}
login($a, $b);
and I know that pass() and user() are true because I changed their positions on the function login() and every time I did this the first argument was returned as true and it didn't check the second one. Does anyone know why this happens?

user and pass1 functions should return true or false, not echo out.

Your user and pass1 functions are not returning an explicit value, so they are implicitly returning the NULL value. As described on this page in the PHP manual the NULL type is converted to false when a boolean is expected. So both your user and pass1 functions return false every time.
The && and and logical operators in PHP use short-circuiting for efficiency (see the first code example on this page of the PHP manual) so in any and statement whose first operand evaluates to false it can never be possible for the whole and statement to evaluate to true, so the second operand (in the case of your code above, the second operand is the call to pass1($b1)) is never evaluated because it would be a waste of time to do so.
Which means you're seeing the user function being called, but never the pass1 function.

Try using this instead:
$a[] = "guy";
$b[] = "g";
function login($a1, $b1)
{
if( user($a1) == true && pass1($b1) == true)
login2($a1, $b1);
else
echo "error!!!!";
}
function login2($a1, $b1)
{
if (array_search($_REQUEST["user"],$a1) == array_search($_REQUEST["pass"],$b1))
echo "you are logged in";
else
echo "erorr";
}
function user($user1)
{
if(in_array($_REQUEST["user"],$user1))
echo "gooooooood?";
}
function pass1($pas)
{
if(in_array($_REQUEST["pass"],$pas))
echo"goooooooood!!!!!!!!";
else
echo "bad";
}
login($a, $b);

Related

Check for multiple null isset values

I am checking if two values are null. If both are null I want to return false, if either or both are not null, I want to return true.
My current code returns true only when both are not null but I want it to return true when either or not null.
// check if both null
if (!isset($myarray['dataone'], $myarray['datatwo']))
{
echo 'false';
);
} else {
echo 'true';
);
}
return $emptytabs;
For that you can use relational operators. AND (&&) OR (||)
By using AND (&&) operators.
if ( (!isset($myarray['dataone']) || (!isset$myarray['datatwo'] ))
{
echo 'false';
}
else
{
echo 'true';
}
By using OR ( || ) operators.
if (isset($myarray['dataone'] && isset$myarray['datatwo'])
{
echo 'false';
}
else
{
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone']) && !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if one or both are null
if ( !isset($myarray['dataone']) || !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone'], $myarray['datatwo']) )
{
echo 'false';
} else {
echo 'true';
}
return $emptytabs;
this approach you provided is totally true , but it only return true if all the provided parameters are set according to php documentations .
so your code should works correctly . except you have unwanted parentheses that should deleted
The simplest way is to use the OR (||) operator. You want to show 'true' if one thing is set OR another thing is set. Just say that with code.
if ( isset($myarray['dataone']) || isset($myarray['datatwo']) ) {
echo 'true';
} else {
echo 'false';
}
Using the AND operator adds pointless complexity by checking that both of the two things are not set in order for it to show 'false'. That's not an intuitive way to think about it, so it doesn't make sense to write the code that way.
DISCLAIMER: This answer is opinionated.

Condition for null value in an array in php

When I am displaying my array by using var_dump I get the following result:
array(1) { [0]=> NULL }
I want to apply a condition that when my array has a null value it should do something. I have tried using array[0]== NULL and array[0]= NULL inside my condition but it does not work. Can anyone tell me what could be the correct condition for it?
PHPs empty() checks if a variable doesn't exist or has a falsey value (like array(), 0, null, false, etc).
<?php
if (!empty($array[0])) {
echo "Not empty";
} else {
echo "empty";
}
?>
or by using is_null
<?php
if(is_null($array[0])) {
echo "empty";
} else {
echo "not empty";
}
?>
or
<?php
if($array[0] === NULL) {
echo "empty";
} else {
echo "not empty";
}
?>
You can do it by several ways:
if(is_null($array[0])) {}
or
if(!isset($array[0])) {}
or
if($array[0] === null) {}
By the way, == makes a comparison, = is an assignment (even in an if statement) and === compares values and type.
$arr = array();
if (!empty($arr)){
//do your code
}
else {
echo "Hey I'm empty";
}

Set and validate return value in IF in PHP

Could I do this in PHP?
if ($Var = $this->test1() == true) {
var_dump($Var);
}
public function test1() {
return true;
}
It echoes true, but I'm not sure if this is the correct way to check such return values.
Yes you can, but write:
if (($var = $this->test1()) === true) {
var_dump($var);
}
To be safe and to alert the reader there is something going on.
I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.
if (($result = slow_process()) !== false) {
return $result;
} else if (($result = slow_process1()) !== false) {
return $result;
} else if (($result = slow_process2()) !== false) {
return $result;
} else if (($result = slow_process3()) !== false) {
return $result;
}
This is overly simplified, but these situations do occur.
You can but there is 2 things you should be aware of :
When you do something like :
if ($Var = $this->test1() == true) {
The operators are confusing :
do you want to do $this->test1() == true and store result $var
do you want to do $var = $this->test1() and compare it with true
In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :
if ($Var = $this->test1() == 5) {
var_dump($Var);
}
public function test1() {
return 3;
}
Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).
What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.
To avoid mistakes, uses parenthesis :
if (($var = $this->test1()) == true) {
You should take care of types :
I give you an example of what could return something castable to true :
function test1() { return true; }
function test2() { return 3; }
function test3() { return 3.42; }
function test4() { return "x"; }
function test5() { return array('x'); } // array() == true returns false
function test6() { return new stdClass(); }
echo test1() == true;
echo test2() == true;
echo test3() == true;
echo test4() == true;
echo test5() == true;
echo test6() == true;
// outputs 111111 (1 = true)
To avoid mistakes, you should use === operator. Your final piece of code becomes :
if (($var = $this->test1()) === true) {
The == true part is unnecessary. What you have is valid syntax, but some find it confusing. You can always do:
$Var = $this->test1();
if ($Var) { ...
Just decide on the standard with your development team.
You can also do:
if ($Var = $this->test1()) {
var_dump($Var);
}
public function test1() {
return true;
}

Working with PHP functions

I have this function that will check if a user already exists in the DB or not:
function checkTwitterAccount($user_id) {
$accountExists = false;
$a = "SELECT * FROM twitterAccounts WHERE user_id='".$user_id."'";
$ar=mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
if ($ac > 0) {
$accountExists = true;
}
return $accountExists;
}
Now when I call this function how do I actually know if the user is or is not in the DB?
I mean how do I call this function and how do I check the result?
Is the below right?
If (checkTwitterAccount($user_id) = true) {
DO THIS
}else{
DO THAT
}
Please help me I am new to it.
Thanks
if (checkTwitterAccount($user_id)) { //true
//do something
} else { //false
//do something
}
if (checkTwitterAccount($user_id) == true) {
//do this
}
else {
//do that
}
You have to use == rather than = as the = operand sets the value to true in the code you wrote, whereas the == operand compares the returned value to true.
Since your returning a true or false value you can simply use:
If (checkTwitterAccount($user_id)) {
//DO THIS
}else{
//DO THAT
}
Note: that your original line:
If (checkTwitterAccount($user_id) = true) {
would result in an assignment error because a single "=" means assign a value which can't be done to a function. You wanted:
If (checkTwitterAccount($user_id) == true) {
because "==" compares a value. Further, == only compares the value so for example 0 is the compares positively with false, any number compares positively with true, if you want to also compare type you us "===" like this:
0 == false //true
0 === false //false
false == false //true
false === false //true
1 == true //true
1 === true //false
true == true //true
true === true //true
function checkTwitterAccount($user_id) {
$user_id = intval($user_id);
$a = "SELECT `user_id` FROM `twitterAccounts` WHERE `user_id` = '".mysql_real_escape_string($user_id)."'";
$ar = mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
return ($ac > 0);
}
if(checkTwitterAccount($someid)) {
// Exists...
} else {
// No such ID in the DB
}
Note that comparison operator is == not = (which is assign).
So you could do:
if(checkTwitterAccount($someid) == true) {
However, it isn't necessary here.
Also remember to sanitize the data in the query.
if (checkTwitterAccount($user_id) == true){
do something if its true
} else {
do something if its flase
}
should work.. given that you provide argument to that function which seems to be
the int.. or id number from id column from users table in the db.
Basically you have a HTML Form that takes in a username and checks the database
for that users id number in users table in the database. Once it has this number it will
pass it on to the function checkTwitterAccount($user_id) if that function returns True that means guessing by the name of the function that the user has a twitter account else he does not have one.
you could do:
if (checkTwitterAccount($user_id) == true){
echo "This user has a twitter account";
} else {
echo "This user does not have a twitter account";
}
You can shorten the orig. function.
function checkTwitterAccount($user_id) {
$a = "SELECT * FROM twitterAccounts WHERE user_id='" . $user_id . "'";
$ar = mysql_query($a) or die("Error selecting twitter account: " . mysql_error());
return mysql_num_rows($ar) > 0; // boolean (will be true or false)
}
Then use the answer from max_. (See comparison operators)

Problem with Boolean Values in PHP

I've some problems with handling Boolean values in PHP. It is a validation script before storing data into database. I wrote a global validator that will validate and return a Boolean value whether the validation was successful .
Here is my code.
//VALIDATE
$isValid = true;
foreach($team as $key=>$val) {
if(!is_array($val)){
$isValid = $isValid && validate($val, $key);
}
}
for($it=0;$it<count($team['members']);$it++){
foreach($team['members'][$it] as $key=>$val) {
$isValid = $isValid && validate($val, $key);
}
}
if(!$isValid) { // EDITED: if(!isValid)
echo "validation error";
exit(1);
}
//END OF VALIDATE
The validate function is working properly but sometimes I end up getting $isValid = true or the other way, when I try with some test cases.
Hmm.. What am I doing wrong here ?
Please check, if this form does the trick:
if( false === $isValid) {
echo "validation error";
exit(1);
}
Note, that ( ! $isValid ) or (false == $isValid ) in some cases return results, which are at first look wrong. See for example the hint in the strpos() documentation.
In fact, the results are fine, since operations line ! or == try to cast operands in a 'useful' way.
That said, it's always better to user the === operator, since it checks values and types of operands. Please see operator overview.
if(!isValid) { falls back to if (!"isValid"), if there is no constant isValid. You probably meant if (!$isValid) {.
if(!isValid) {
isValid has no dolar, (you need to give variables in PHP some cash) so:
if(!$isValid) {
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators in PHP. Hope it will helpful:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a=10;
$b=20;
if($a>$b)
{
echo " A is Greater";
}
elseif($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c=30;
$d=40;
//if(($a<$c)AND($b<$d))
if(($a<$c)&&($b<$d))
{
echo "A and B are larger";
}
if(isset($d))
$d=100;
echo $d;
unset($d);
?>
<?php
$var1=2;
switch($var1)
{
case 1:echo "var1 is 1";
break;
case 2:echo "var1 is 2";
break;
case 3:echo "var1 is 3";
break;
default:echo "var1 is unknown";
}
?>
</body>
</html>
I think the problem is that your $isValid variable can be changed many times in the loops and by the end of your code simply applies to the last value in your final loop.
You should set it to true initially and then only set it to false IF your validity check fails - not simply assign its value based on every single validity check.

Categories