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
Related
In Javascript I would do something like this-
var time_array = [];
if ((previousTime > time_array[i]) || (time_array[i] === undefined) )
{
//Do Something
}
I want to do something similar in PHP
$time_array = array();
if (($previousTime> $time_array[$i]) || ($time_array[$i] === undefined) ))
{
//Do Something
}
I can do this very easily in Javascript , but I am a little confused about it in PHP.
$time_array = array();
if (!isset($time_array[$i]) || $previousTime > $time_array[$i])
{
//Do Something
}
It will first check if the variable is set and if it is not, the second condition will never be evaluated, so it's safe to use.
Edit: isset() checks whether a variable is declared and is set to a non-null value. You may want to use: if ($time_array[$i] === null) instead (that would be probably more similar to JS's undefined).
Just use this:
http://www.w3schools.com/php/func_array_key_exists.asp
if (array_key_exists($i,$time_array))
{
echo "Key exists!";
}
This below is printing hello even though the statement is false
$Originating_country_region = $country_region[$i]['region']; // value of var is AM after assigning
$order_shipping_country_region = $country_region[$i]['region']; // value of var is EU after assigning
if(isset($Originating_country_region) == "EU" && isset($order_shipping_country_region) == "EU")
{
echo "Hello";
}
You're testing the return value of isset, and not the contents of the variables directly. Try:
if((isset($Originating_country_region) && $Originating_country_region) == "EU") && (isset($order_shipping_country_region) && $order_shipping_country_region == "EU"))
This checks that the codes are first of all set, and then checks their values.
It's a useful trick to learn :-)
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";
}
}
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';
}
?>
I'm using a variable in Javascript which will be set via Php e.g. var usesInterview = <?php echo 1;?>
If not, then var usesInterview = <?php echo 0;?>
How best should I handle this in my code? There will be a If statement to check for the variable and determine the route to take.
I've tried using typeof() == 1 and when I set it to 0, it still carries out the routine as if it where 1.
Why not set it with javascript:
usesInterview = 1;
Even if you set it with PHP, you can check like this:
if (usesInterview === 1){
// variable is equal to 1
}
else if (usesInterview === 0){
// variable is equal to 0
}
Notice the === to check for both type as well as value. If you don't want to check for type, you need to use == like this:
if (usesInterview == 1){
// variable is equal to 1 or "1" or true
}
else if (usesInterview == 0){
// variable is equal to 0 or "0" or "" or false
}
You should avoid the later approach when you are sure about both type as well as value.
More Information:
http://w3schools.com/JS/js_comparisons.asp
There are so many ways you can do it... Ie
var usesInterview = <?php echo [0|1];?>
usesInterview ? goingTrueWay() : goingFalsegWay();
or
<?php echo [0|1];?> ? goingTrueWay() : goingFalseWay();
or something like this:
var waysCollection = {
0: function () {...} //routine for usesInterview == 0
1: function () {...} //routine for usesInterview == 1
}
waysCollection[<?php echo [0|1];?>]();
also you can use one of the early suggestion:
if (<?php echo [0|1];?>) {
// truthy branch
} else {
// falsy branch
}
BTW, if you want usesInterview to be a boolean, yes/no trigger, - use true/false not 0/1. Its easier to read and understand later. For ex
var usesInterview = <?php echo [false|true];?>
if (usesInterview) {
//do this if `true`
} else {
//do this if `false`
}
typeof will return the type of the value - "number" in this case. You're using a non-strict equality check (==) so "number" == 1 is true.
Just check the value, using type-strict equality operator (===):
if (usesInterview === 1) {
// do something
}
else if (usesInterview === 0) {
// do something else
}
Read more about JavaScript comparison operators at https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators.
When usesInterview is 1 it's truthy. So it's as simple as:
if (usesInterview) {
// truthy branch
} else {
// falsy branch
}