Checking If Then statements in PHP - php

When I write an if statement, I have it check a variable like so:
if(isset($_GET['username']){
echo "set";
} else {
echo "unset";
}
How could I get my if statement to check if two variables are set similiar to this:
if(isset($_GET['username'] & $_GET['firstname'])){
echo "set";
} else {
echo "unset";
}
So basically how do I check two things in an if statement at once?

Check out the PHP Manual on control structures and logical operators:
if(isset($_GET['username']) && isset($_GET['firstname'])) {
echo "set";
} else {
echo "unset";
}
Using the single & is doing a bitwise operation, which is most certainly not what you want.
and is also a synonym to the && syntax, as the other answers have shown.
EDIT: As pointed out in the comments, you can check if two variables are isset by passing them both to the isset function. However, if you ever wanted to do some other sort of operation you would need to do the logical operators above.

if ( isset($_GET['username'], $_GET['firstname']) ) {
echo 'Set!';
}
isset takes multiple arguments and if multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

if ( isset($_GET['username']) && isset($_GET['firstname']) )

Try using the && operator (logical and) rather than & (binary and)
so if isset returns true for both then the if returns true otherwise the if will return false.

yes, or
echo ( (isset($_GET['username']) && isset($_GET['firstname'])) ? "set" : "unset" );

if (isset($_GET['username']) AND isset($_GET['firstname']))
{
echo "set";
}
else
{
echo "unset";
}

if (isset($_GET['username']) && isset($_GET['firstname']))
{
echo "set";
}
else
{
echo "unset";
}
For reference: PHP's operators

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.

Correct way to check if value exists and is an array with items

So one way to do it would be..
if(isset($arrayVar)) {
if(is_array($arrayVar)) {
if(count($arrayVar) > 0) {
// Success
print_r($arrayVar);
}
}
}
Are there any better ways?
You can do it using is_array and empty:
if (!empty($arrayVar) && is_array($arrayVar)) {
// ...
}
empty() will check if isset and not empty at once.
if (!empty($arrayVar) && is_array($arrayVar))
!empty covers both isset and empty arrays (all falsey values in fact), you then just need to confirm that it's also actually an array.
You can check like this,
if(is_array($arrayVar) && sizeof($arrayVar) > 0)
{
echo 'Array value exists';
}
else
{
echo 'array empty or it is not array';
}

php for true/false parsing of content

I'm trying to create a simple yes/no or true/false boolean type line to parse content depending on the answer.
Like this:
<?php
dangerous = "yes";
?>
<?php
dangerous = "no";
?>
A block down here similar to isset, that will parse if the answer above is yes, and to not appear if anything else other than yes is written.
<?php if dangerous = yes ?>
Dangerous content here.
<?php endif; ?>
I'm new to PHP, so I'm not sure what route to go with here.
Firstly, this line here will always evaluate to true, because you are using a single = which is an assignment operator:
if($dangerous = 'yes') // this will always be true
You need to use == for a comparison operator, or === for strict comparison which takes variable types and values into consideration as well. For more info on the difference between the comparison operators, see here.
The way you're doing it currently is pretty widely used, but is not the best practice. Your variable $dangerous will be set every time, and you need to check for the value of it to determine whether to evaluate your conditions or not:
if($dangerous == 'yes') {
// do dangerous stuff
}
Better practice, as you've said, is to use a boolean variable which will evaluate to true or false (above example in this same test will evaluate to true in both cases):
$dangerous = true; // or false;
if($dangerous) {
// do dangerous stuff
}
Likewise, if it's not dangerous:
if(!$dangerous) {
// pretty safe, but this will evaluate to true for false, null, zero etc
}
In this example, !$dangerous will evaluate to true when $dangerous is null, zero etc, so if you need a strict comparison for the value of false, you'll need the === comparison operator:
if($dangerous === false) {
// false evaluates to true when comparing for a false value
// false evaluates to false when comparing for a null value
}
Better to use a boolean variable over a string representation of a result in most cases. Something to keep in mind though is that if your your boolean variable represents the return of a function call, it might not always be consistent.
if($dangerous == "yes"){
//do something
} else {
//do something else
}
<?php
if($yes){
?>
<b>This is my HTML.</b>
<?php
}else{
?>
<b>This is other HTML.</b>
<?php
}
?>
<?php if ($dangerous === 'yes'): ?>
yes
<?php endif; ?>
<?php if ($dangerous == 'no'): ?>
no
<?php endif; ?>
The issue is the use of an assignment operator (=) when you should be using a comparison operator (== / ===) and comparing variables and value correctly.
For your case
<?php
if($dangerous === "yes"){
//Dangerous content here.
}
?>
Use code like this:
$dangerous = true; // or false if no
// check result
if ($dangerous) {
// dangerous!
}
Define the conditions for dangerous content and apply php expeptions:
if(dangerous){
try {
echo inverso(5) . "\n";
echo inverso(0) . "\n";
} catch (Exception $e) {
echo 'Excepción capturada: ', $e->getMessage(), "\n";
}
}

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.

Compare variables PHP

How can I compare two variable strings, would it be like so:
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
And to check to see if a $_GET[] variable is present in the url would it be like this"
$myVars = $_GET['param'];
if ($myVars == NULL) {
//do code
}
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
$myVar = $_GET['param'];
if (isset($myVar)) {
//IF THE VARIABLE IS SET do code
}
if (!isset($myVar)) {
//IF THE VARIABLE IS NOT SET do code
}
For your reference, something that stomped me for days when first starting PHP:
$_GET["var1"] // these are set from the header location so www.site.com/?var1=something
$_POST["var1"] //these are sent by forms from other pages to the php page
For comparing strings I'd recommend using the triple equals operator over double equals.
// This evaluates to true (this can be a surprise if you really want 0)
if ("0" == false) {
// do stuff
}
// While this evaluates to false
if ("0" === false) {
// do stuff
}
For checking the $_GET variable I rather use array_key_exists, isset can return false if the key exists but the content is null
something like:
$_GET['param'] = null;
// This evaluates to false
if (isset($_GET['param'])) {
// do stuff
}
// While this evaluates to true
if (array_key_exits('param', $_GET)) {
// do stuff
}
When possible avoid doing assignments such as:
$myVar = $_GET['param'];
$_GET, is user dependant. So the expected key could be available or not. If the key is not available when you access it, a run-time notice will be triggered. This could fill your error log if notices are enabled, or spam your users in the worst case. Just do a simple array_key_exists to check $_GET before referencing the key on it.
if (array_key_exists('subject', $_GET) === true) {
$subject = $_GET['subject'];
} else {
// now you can report that the variable was not found
echo 'Please select a subject!';
// or simply set a default for it
$subject = 'unknown';
}
Sources:
http://ca.php.net/isset
http://ca.php.net/array_key_exists
http://php.net/manual/en/language.types.array.php
If you wanna check if a variable is set, use isset()
if (isset($_GET['param'])){
// your code
}
To compare a variable to a string, use this:
if ($myVar == 'hello') {
// do stuff
}
To see if a variable is set, use isset(), like this:
if (isset($_GET['param'])) {
// do stuff
}
All this information is listed on PHP's website under Operators
http://php.net/manual/en/language.operators.comparison.php

Categories