php for true/false parsing of content - php

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";
}
}

Related

use html localStorage in PHP

My main question is, why the below code prints out:
false
boolean value true
I would expect the variable "boolean" value is also false
I want to store some data in javascript and later use it in PHP, is it even possible?
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Storage test?</title>
</head>
<body>
<script type='text/javascript'>
localStorage.save = 'false';
</script>
<?php
$boolean = "<script type='text/javascript'>" .
"document.write(localStorage.save);".
"</script>";
echo $boolean;
if($boolean = 'true'){
echo "<p>boolean value true</p>";
} else {
echo "<p>boolean value false</p>";
}
?>
</body>
Like said, you're not comparing, but assigning because of the single equal sing = in the if statement.
Next to that you cannot directly read the localStorage from PHP. So even if you had a double equals == to compare, then it would still outout boolean value true.
That is because you put a string inside $Boolean:
$boolean = "<script type='text/javascript'>document.write(localStorage.save);</script?";
You're not evaluating any JavaScript code like that.
When a PHP variable contains something, wether it be a string or number etc. it will always evaluate to true inside an if statement. Unless the value is either false, 0 or null.
To compare a real Boolean value you have to use an explicit compare. You do that with three equal signs ===.
if ( $someBool === true )
{ // do stuff }
But no, you cannot directly get the localStorage value from JS to PHP. You'd need an Ajax call to pass it back to PHP. And I think that is what you're ultimately trying to do.
if($boolean = 'true'){ <-- this line
echo "<p>boolean value true</p>";
} else {
echo "<p>boolean value false</p>";
}
You are not comparing the $boolean variable with 'true', but assigning the value 'true'.
Try two equal signs.
I'm not even sure what you're doing is possible. But the equal sign is definately a problem.
I guess it's a typo in the if you make
if($boolean == 'true'){
....
}
One = is to assign, comparison is either == or ===.
This example displays "Hello":
<?php
function getData()
{
return 'Hello';
}
if ($data = getData()) {
echo $data;
}
This example displays "23":
<?php
function getData()
{
return 'Hello';
}
$data = getData()
if ($data === 'hello') {
echo 1;
}
if ($data == 'hello') {
echo 2;
}
if ($data === 'Hello') {
echo 3;
}
Using = will only assign $boolean with that value and will return true because it's not false, 0, or null. Try using == or ===. :)

The best practice for not null if statements

I've been writing my "If this variable is not empty" statements like so:
if ($var != '') {
// Yup
}
But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:
if (!($error == NULL)) {
/// Yup
}
This actually looks longer than my approach, but is it better? If so, why?
Rather than:
if (!($error == NULL))
Simply do:
if ($error)
One would think that the first is more clear, but it's actually more misleading. Here's why:
$error = null;
if (!($error == NULL)) {
echo 'not null';
}
This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:
$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;
The second conditional if ($error) makes it more clear that type casting is involved.
If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)
It is good to know exactly what is in your variable, especially if you are checking for uninitialized vs null or na vs true or false vs empty or 0.
Therefore, as mentioned by webbiedave, if checking for null, use
$error !== null
$error === null
is_null($error)
if checking for initilized, as shibly said
isset($var)
if checking for true or false, or 0, or empty string
$var === true
$var === 0
$var === ""
I only use empty for ''s and nulls since string functions tend to be inconsistent. If checking for empty
empty($var)
$var // in a boolean context
// This does the same as above, but is less clear because you are
// casting to false, which has the same values has empty, but perhaps
// may not one day. It is also easier to search for bugs where you
// meant to use ===
$var == false
If semantically uninitialized is the same as one of the values above, then initialize the variable at the beginning to that value.
$var = ''
... //some code
if ($var === '') blah blah.
Why just don't
if (!$var)
There are ways:
<?php
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
?>
Another:
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
?>
To check if it's empty:
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>

php "if" condition mystery

I am running into a funny problem with a mischievous "if" condition :
$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Why does the if condition pass?
Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?
The problem here is that you're putting your expressions in strings!
Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.
To fix this you just need to take your expressions out of the strings. It should look like this:
$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false
if ($condition) {
echo 'blah';
} else {
echo 'foo'; // This will be output
}
You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.
Those aren't conditions, they're strings.
$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Because you're not checking those variables, it's saying if (String) will always return true. (unless "")
You should be doing:
if(53==56 || 53==57 || 53==58)
{
echo "blah";
}
else
{
echo "foo";
}
All $condition* variables will evaluate to true. This is how PHP sees it:
if("53==56" || "53==57" || "53==58")
What you want is this:
$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;
It's because you're evaluating a string, and strings other than empty strings evaluate to true.
You are concatting a string together, a non-empty string equals TRUE in php.
Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition)).
String always evaluate to true if its not empty
And btw php make implicit conversion to boolean

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

Checking If Then statements in 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

Categories