I'm wondering if there is any way to make this code shorter. I'm using 2 if statements and I'm looking to only use one. The things is $user is the session and if you check if $user->userId exists on the same line, the code will error when no session exists. Caused by requesting the userId from an object that does not exist. That's pretty logical but now is there any solution?
if ($user != null) {
if ($user->userId == 1) {
..
}
}
How about using the && operator:
if ($user && $user->userId == 1) {
//...
}
You can add as many sentences as you want, as long as they are properly built, in this case:
if (($user != null) && ($user->userId == 1)) {
or you could simply:
if ($user && ($user->userId == 1)) {
if ($user) just checks if the variable is set, or if it is not null.
You want to use the && operator. It means and
if ($user && $user->userId == 1) {
// do some things
}
You may also want to look into the || operator, it means or.
The && operator will return true ONLY if the two predicates return true.
The || operator will return true as long as one of the predicates return true.
Related
I'm using this in my code but I think it can be improved and can be done a simpler way?
if($phaseOne == true && $phaseTwo == true && $phaseThree == true) {
}
You can do it like this:
if($phaseOne && $phaseTwo && $phaseThree) { ... }
Or use ternary operator, if you're trying to define a variable on the basis of these conditions like this:
$var = ($phaseOne && $phaseTwo && $phaseThree) ? true : false;
Hope this helps!
Assuming you have an array with an arbitrary number of logical variables:
$logical = array($phraseOne,$phraseTwo,....);
$allTrue = array_reduce($logical, function ($x,$y) {return $x && $y;},true);
if($allTrue) {
}
Do just:
if($phaseOne && $phaseTwo && $phaseThree)
You don't need to compare it against true.
if ($phaseOne && $phaseTwo && $phaseThree) {
}
This occurs because the result of any comparison is a boolean:
var_dump(1 == 1); // bool(true)
var_dump(1 == 2); // bool(false)
Also if you variable contains a number, it can be used directly:
if (1) {
// This will be executed
}
if (0) {
// This will not be executed
}
Zero will be always be treated as false, any other number (positive or negative) will be true.
Unless you need to check each variable as explicitly identical to a boolean or variable, (see this stack overflow thread)
I'd do it this way
if ($phaseOne && $phaseTwo && $phaseThree) {}
Otherwise, I'd do it this way
if ($phaseOne === true && $phaseTwo === true && $phaseThree === true) {}
Try with this:
($phaseOne && $phaseTwo && $phaseThree) ? {//do something} : '';
Although I think it is arbitrary, controlversial, trivial, and won't preach the use of this, just for fun and learning - here's some typical php variable type juggling that will work also and takes up the least space... efficient in terms of source code length.
if($phaseOne*$phaseTwo*$phaseThree) { ... }
I have 2 URLs say
http://localhost/xyz?language=en
http://localhost/xyz?language=es
for which I want to check if language parameter has something other than en/es, then it should redirect to some http://localhost/xyz/errorpage
For this I have below code:
if(isset($_GET['language'])){
if(($_GET['language'] !== "en") || ($_GET['language'] !== "es")){
header('Location: /xyz/errorpage');
}
}
But practically when I execute the any of the 2 URLs or putting value of language parameter to something different than en/es:
http://localhost/xyz?language=en
http://localhost/xyz?language=es
http://localhost/xyz?language=esdfsdf
I am redirected to errorpage
Cannot understand the issue with code.
Replace || by &&.
The reason :
You want to redirect only if this is not en AND not es.
change the if statment to && instead of || or your condition will be always false.
if(isset($_GET['language'])){
if($_GET['language'] !== "en" && $_GET['language'] !== "es"){
header('Location: /xyz/errorpage');
}
}
You have bad condition, or better, operator.
Use && instead of ||, or in_array().
if(($_GET['language'] !== "en") && ($_GET['language'] !== "es")) {
Using in_array() function:
if (!in_array($_GET['languge'], array('en', 'es'))) {
header ();
}
Condition if ($a != 'x' || $a != 'y') is always true, first or the second part of condition has be true. There are no other ways.
I was writing in PHP and making so the page was declared by get method. For an example if it were index.php?page=home it would take home and compare to other strings and... ya include the home BUT the compression in the if statement dosnt work... I have also write that if get method == start then dont show the side news but it still showed it!
Here's my code:
if(isset($_GET['page']) && $_GET['page'] == 'start'){
$adbool = false;
}else{
include('inc/main.php');
}
And here is the if statement for deleting side news:
if(isset($adbool) && !$adbool == false){
include('inc/ad.php');
}
and remember this !$adbool == false is not equal to this $adbool != false
You better understand this part as well !$adbool == false;
!$adbool means that $adbool is equal to false;
so !$adbool == false; means if false=false hence this condition always set to to true.
Thats why your logic is failing
Change this
if(isset($adbool) && !$adbool == false){
include('inc/ad.php');
}
To this
if($adbool == TRUE){//simply check weather its set to to true or not
include('inc/ad.php');
}
use
if(isset($adbool) && $adbool){
include('inc/ad.php');
}
this will check if $adbool is set, and if it's set to true.
I want to check the GET variables are not empty, I tried ways but they didn't work.
So I had the code like this:
$u = isset($_GET["u"]);
$p = isset($_GET["p"]);
if ($u !== "" && $p !== "") {
//something
} else {
//do something
}
The I checked the code by sending create.php?u=&p=, but the code didn't work. It kept running the //do something part. The I tried:
echo $u;
echo $p;
It returned 1 and 1. Then I changed it to:
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "") {
//something
} else {
//do something
}
But it continued to run //do something.
Please help.
You can just use empty which is a PHP function. It will automatically check if it exists and whether there is any data in it:
if(empty($var))
{
// This variable is either not set or has nothing in it.
}
In your case, as you want to check AGAINST it being empty you can use:
if (!empty($u) && !empty($p))
{
// You can continue...
}
Edit: Additionally the comparison !== will check for not equal to AND of the same type. While in this case GET/POST data are strings, so the use is correct (comparing to an empty string), be careful when using this. The normal PHP comparison for not equal to is !=.
Additional Edit: Actually, (amusingly) it is. Had you used a != to do the comparison, it would have worked. As the == and != operators perform a loose comparison, false == "" returns true - hence your if statement code of ($u != "" && $p != "") would have worked the way you expected.
<?php
$var1=false;
$var2="";
$var3=0;
echo ($var1!=$var2)? "Not Equal" : "Equal";
echo ($var1!==$var2)? "Not Equal" : "Equal";
echo ($var1!=$var3)? "Not Equal" : "Equal";
echo ($var1!==$var3)? "Not Equal" : "Equal";
print_r($var1);
print_r($var2);
?>
// Output: Equal
// Output: Not Equal
// Output: Equal
// Output: Not Equal
Final edit: Change your condition in your if statement to:
if ($u != "" && $p != "")
It will work as you expected, it won't be the best way of doing it (nor the shortest) but it will work the way you intended.
Really the Final Edit:
Consider the following:
$u = isset($_GET["u"]); // Assuming GET is set, $u == TRUE
$p = isset($_GET["p"]); // Assuming GET is not set, $p == FALSE
Strict Comparisons:
if ($u !== "")
// (TRUE !== "" - is not met. Strict Comparison used - As expected)
if ($p !== "")
// (FALSE !== "" - is not met. Strict Comparison used - Not as expected)
While the Loose Comparisons:
if ($u != "")
// (TRUE != "" - is not met. Loose Comparison used - As expected)
if ($p != "")
// (FALSE != "" - is met. Loose Comparison used)
You need !empty()
if (!empty($_GET["p"]) && !empty($_GET["u"])) {
//something
} else {
//do something
}
Helpful Link
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "")
why are you using "!==" and not "!=".
to always simplify your problem solve the logic on paper once using the runtime $u and $p value.
To check if $_GET value is blank or not you can use 2 methods.
since $_GET is an array you can use if(count($_GET)) if you have only u and p to check or check all incoming $_GET parameters.
empty function #Fluffeh referred to.
if($_GET['u']!=""&&$_GET['p']!="")
Hope it helps thx
In you code you should correctly check the variable existence like
if ($u != NULL && $p != NULL && $u != 0 && $p != 0) {
//something
} else {
//do something
}
Wow! I was so dumb... isset returns a boolean. I fixed my problem now. Thank you for answering anyway :)
This fixes:
$u = $_GET["u"];
$p = $_GET["p"];
I'm sorry for the vaguely described title. This is what I want:
if($a[$f] === false || $a[$g] === false || $a[$h] === false || $a[$i] === false || $a[$j] === false)
{
// do something
}
I want to do something with the condition that actually triggered the statement (if a[$f] = true and a[$g] = false, I want to do something with $g).
I know that in this case, the first statement that went true (i.e. $a[$g] == false) triggers. But is there any way to do something with $g? I've never seen this in my programming life before and can't seem to find anything about it.
Thanks in advance.
--- Edit ---
I forgot to mention: I'm using a function on all the array data. So, shortened, I get this:
if(valid($a[$f]) === false || valid($a[$g]) === false)
{
// do something
}
--- Edit 2 ---
This piece of OOP-based PHP, where I'm in a class, is my code.
if($this->validatedText($product[$iName]) == false ||
$this->validatedUrl($product[$iUrl]) == false ||
$this->validatedNumber($product[$iTax]) == false ||
$this->validatedValuta($product[$iPrice]) == false ||
$this->validatedText($product[$iArticleNumber]) == false ||
$this->validatedText($product[$iDescription]) == false ||
$this->validatedText($product[$iMetaDescription]) == false ||
$this->validatedText($product[$iTitle]) == false)
{
// do something with the first iVariable
}
Simplest solution will be
if(false!==($sIndex = array_search(false, $a, 1)))
{
//your $sIndex is first index with false value
}
if you want all keys, you may use array_filter(), like this:
$rgFalse = array_keys(array_filter($a, function($x)
{
//here valid is your function
return false===valid($x);
}));