Echo a variable if condition met - php

I just started with PHP... This works so far:
$value = get_field( "transmissie" );
if( $value ) {
echo $value;
} else {
echo 'empty';
}
The value variable can be "Manual" or "Automatic"
What I'm trying to do is to check if the value is "Manual" and then I want to echo 'Manual', but if the value is 'Automatic' then I want to echo this:
Automatic
Can someone put me in the right direction? :)
Thanks!

In PHP and many other languages, == is used to test whether two values match. So in your case it's a simple usage of that operator to get what you want:
if( $value == "Manual" ) {
echo $value;
} else {
echo 'Automatic';
}
N.B. If you want to be sure that both values are of the exact same data type then you would use === instead. (e.g. "1" == 1 will return true, because it considers that the string "1" is the same as the integer 1, whereas "1" === 1 will return false - it considers they are not the same because they are not the same data type.)
There's more information in the manual here: https://www.php.net/manual/en/language.operators.comparison.php

Related

Check if 2 vars are not in array in php

This is one is confusing me.
I am trying to check if 2 vars are not in an array with an OR, but it returns the opposite results than the expected.
Does 2 !in_array, in conjunction with an OR, creates 2 negatives = positive?
The case:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) || !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Since 2 is in the array, I expect the script to echo "In Array", but it echoes "Not in Array". If I remove the second !in_array after the OR, it echoes "In Array". If I change the OR with an AND, it echoes "In Array".
It doesn't make much sense, or I am just that confused at the moment. Can someone give some input?
The problem is you are using || instead of &&. What the logical OR (||) does is that it checks the first condition and if it is true then it does not test the other conditions in the if statement. Here is the revised code:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Hope this helps!
Try this:
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
This will ensure that when both (&&) 0 and 2 are not in the array, it prints "Not in array"
As stated in my comment, you should be checking that the first value and the second value are not in the array: !in_array(2, $user->groups) && !in_array(0, $user->groups).
For two conditions, I would consider the following suggestion overkill but you may find it useful if you want to search for a larger number of values:
$arr = array(1,2,3);
$search = array(1,2);
$all_in = function($prev, $curr) use ($arr) {
return $prev && in_array($curr, $arr);
};
if (array_reduce($search, $all_in, true)) {
echo 'all values in $search are in $arr';
}
else {
echo 'some of the values in $search are not in $arr';
}
array_reduce applies the callback function $all_in to each of the values of the $search array and keeps track of a boolean value (initialised to true) that remains true as long as all the values are in the array $arr.
As I said, this approach isn't particularly useful if you're only looking for two values but one benefit is that you can easily add values to the $search array without changing any of the other code.

PHP Variable Randomly Changes

I have encountered a very weird and concerning problem in some of my PHP code. A variable that I have returns true in an IF statement when it clearly should return false.
$pr = $_SESSION['fin_print_printer']; //this should equal 0
print $pr; //this returns 0, as it should
if($pr == "L"){
print "local";
} else {
print "serve";
}
print $pr; //this returns 0 again, as it should
This prints "local" in my script (in between the two zeros) and does not print "serve". With over 100,000 lines of code in my project, I've not experienced this issue yet, and now I can't figure out what is going on.
If I do if($pr === "L"), then it works as expected, but the above does not.
PHP is trying to typecast 'L' into an int, which results in 0.
intval('L'); // 0
Change your code into the following so it will take types into account:
if($pr === "L")
{
print "local";
}
else
{
print "serve";
}
Or manually typecast $pr to a string.
// You can also to (string)$pr ("0" instead of 0)
if(strval($pr) == "L")
{
print "local";
}
else
{
print "serve";
}
Maybe if you use typecasting (I did't check it):
if ( (string)$pr == "L" ) {
print "local";
} else {
print "serve";
}
Little known approach: You can also do the casting like
if ("L" == $pr) {
Because with loose comparisons, PHP casts the right value to the left value's type, and as you've already been made aware, while string(1)"L" is casted to int(0), int(0) is casted to string(1)"0".

if condition with one variable for understanding [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regarding if statements in PHP
this is a simple question. But Here I need to know how if condition work with only one variable.
$category='';
if ($category) {
}
can you tell what actually check in If condition? Condition has only one variable..
is it checking variable is TRUE or FALSE?
PHP is a weak typed language. To understand what is evaluated in the if condition, see the conversion rules for booleans.
Quoting from the manual:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Therefore, your condition will be evaluated as FALSE, since $category == '' and (bool) '' === FALSE
Type 1
$category = '';
if ($category) {
echo 'category';
} else {
echo 'no category';
}
// Output : no category
Type 2
$category = TRUE;
if ($category) {
echo 'category';
} else {
echo 'no category';
}
// Output : category
Type 3
$category = '';
if (!empty($category)) {
echo 'category';
} else {
echo 'no category';
}
// Output : no category
Type 4
$category = 0;
if (!empty($category)) {
echo 'category';
} else {
echo 'no category';
}
// Output : no category
Type 5
$category = 0;
if (isset($category)) {
echo 'category';
} else {
echo 'no category';
}
// Output : category
this will check for TRUE
if ($category) {
}
You empty string will be casted to a boolean value, false in this case. See the manual on Booleans.
This checks whether variable evaluates to true, it's an equivalent of:
if( (bool)$category === true) )
Yes It is checking TRUE or FALSE. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.
if ($category) {
}
Will simply check if $category has a value. You did not give $category a value.
In this case, it will give a FALSE.
The block of the if-condition activates whenever the evaluated statement is true.
The empty string in PHP evaluates to false, so this will not be activated. You could be more specific by specifying what you expect, for example:
$category = '';
if (empty($category)) {
}
... in case you expect this to activate whenever it is empty. It really depends on what you are trying to to but like this I assume the condition is never met.

Extremely simple foreach and if - can't figure out why it isn't working - PHP

I've done a million if and foreach's in scripts before, but this one I can't seem to figure out. It just isn't working...? Maybe it's one of those things that if you look at it 100 times you won't see the error and need a second set of eyes. Okay, so, here's the code:
private function removeResultsByUID() {
foreach ($this->searchResults as $key => $value) {
if (!$this->searchResults[$key]['authorUID'] == $this->searchUID)
unset($this->searchResults[$key]);
}
return;
}
Simple enough, it is part of a forum search program that attempts to remove search results based on a username they might have entered to filter by. Problem is, it isn't filtering, so I went into test mode and adjusted the code to see what was going on:
private function removeResultsByUID() {
foreach ($this->searchResults as $key => $value) {
var_dump($this->searchResults[$key]['authorUID']);
echo ' ';
var_dump($this->searchUID);
echo '<br />';
if (!$this->searchResults[$key]['authorUID'] == $this->searchUID) {
echo "This isn't a match";
unset($this->searchResults[$key]);
}
}
die();
return;
}
Okay, so a simple way to test, dump the variables I'm iffing to see what their values are set to (using var_dump instead of echo to ensure they are both string types for my knowledge). Then I add an echo to the if to see when the if condition triggers. Then kill the script to view the results. I toss in some search criteria with a username, the program changes it to a userID based on a table in the DB, every result it grabs from the search that matches adds the author's user ID to the result array. Here is what I get:
string(1) "3" string(1) "3"
string(1) "1" string(1) "3"
string(1) "1" string(1) "3"
string(1) "1" string(1) "3"
It looks like the if is never triggering even though the dumped variables the if is using makes it seem as if it should trigger for the last 3 iterations. I've stared at it for an hour. What the hell did I do wrong? I'm going to kick myself for a stupid mistake I'm sure, I just can't see it. Thanks for any help!
you want to use != and not !$x == $y:
if ($this->searchResults[$key]['authorUID'] != $this->searchUID) {
// or: if(!($this->searchResults[$key]['authorUID'] == $this->searchUID)) {
// your code here
}
!$this->searchResults[$key]['authorUID'] will either be true or false (most likely false, unless you have an id of "0"). so your comparison turns into false == $this->searchUID – not so likely to match.
I assume that searchResults is an array of array
You loop through each element like so:
foreach ($this->searchResults as $key => $value)
Then you don't use the value at all:
if (!$this->searchResults[$key]['authorUID'] == $this->searchUID)
I think you wanted to say:
if (value['authorUID'] != $this->searchUID) // (fixed Boolean logic)
and you can further optimize it by using a reference in the foreach:
foreach ($this->searchResults as $key => &$value)
if (!$this->searchResults[$key]['authorUID'] == $this->searchUID)
You're negating the first term and then comparing to the second term. Add parentheses or use !=.
You have !$this->searchResults[$key]['authorUID']
IF you want them to be equal remove the !
If you want them to not be equal then it should be
if ($this->searchResults[$key]['authorUID'] != $this->searchUID)
Could it be the placement of the ! in your if statement?
Won't your if statement equate to:
if ([opposite-of]$this->searchResults[$key]['authorUID'] (false) == $this->searchUID (true)
Here's your problem:
if (!$this->searchResults[$key]['authorUID'] == $this->searchUID)
It should be:
if ($this->searchResults[$key]['authorUID'] != $this->searchUID)
I'm not 100% sure (didn't check), but if you ! an integer, it returns == 0. IE: an integer is "true" if it's not zero. So you have "!true == integer", or, "false == integer", and since your other integer is non-zero, you have "false == true" as your test.
You have a simple logic error in your if statement. This is what you have:
if (!$this->searchResults[$key]['authorUID'] == $this->searchUID)
Looking at this, you negate $this->searchResults[$key]['authorUID'] before the comparison.
Negating a string, turns it to false. So you are always checking:
if(false == $this->searchUID)
I'm not entirely sure what you were trying to check, but that should push you into the right direction of fixing it.
Edit:
As I'm looking, I realized the var dump is 'string(1) "3"'. If this is an ID, wouldn't it make more sense (and be faster) to use simple int, rather than string comparisons?
You want to use ! and if 'authorID' is equal to 'searchUID' and 'authorId' is an array you want to try a simplier, elegant and faster way to loop through your array:
if ( ! $this->searchResults [$key] [ 'authorId' ] [ $this->searchUID ] ) {
Here is the whole function:
private function removeResultsByUID() {
foreach ( $this->searchResults as $key => $value ) {
if ( ! $this->searchResults[$key] [ 'authorId' ] [ $this->searchUID ] ) {
unset($this->searchResults[$key]);
}
}
return;
}

Test for query variable exists AND ALSO is set to a particular value?

I want to check if a query variable exists or not. Then I would do something based on that query value. If it exists and is true, do something. If it doesn't exist or is false, do something else such as show a 404 page.
e.g If the url was domain.com?konami=true
if (condition) {
//something
} else {
//show404
}
OPs question is a bit unclear. If you assume that he wants to check that konami is a $_GET parameter and that it has the value of "true" do:
if (isset($_GET["konami"]) === true && $_GET["konami"] === "true") {
// something
} else {
// show 404
}
The problem with the current accepted answer (by Cameron) is that it's lacking the isset check (which is unforgivable, it is objectively wrong). The problem of the highest voted answer (by Jan Hancic) is that it lacks the === "true" check (which is debatable, it depends on how your interpret the question).
Note that && is a lazy-and, meaning that if the first part is false, the second part will never be evaluated, which prevents the "Undefined index" warning. So the order of the statements is important.
Also note that $a === true is not the same as $a === "true". The first compares a boolean whereas the second compares a string.
If you do weak comparison $a == true you are checking for truthy-ness.
Many values are truthy, like the string "true", the number 1, and the string "foo".
Examples of falsy values are: empty string "", the number 0 and null.
"true" == true; // true
"foo" == true; // true
1 == true; // true
"" == true; // false
0 == true; // false
null == true; // false
"true" === true; // false
"true" === false; // false
There is a little confusion around what value should be tested. Do you want to test the konami parameter for being true in the sense of boolean, i.e. you want to test konami parameter for being truthy, or do you want to test if it has string value equal to "true"? Or do you want to test konami parameter for any value in general?
I guess what is wanted here is to test konami for a given string value, "true" in this case, and for being set at the same time. In this case, this is perfectly enough:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
...
if ($_GET['konami'] == "true")
...
This is enough, because if the $_GET['konami'] is unset, it cannot be equal to any string value except for "". Using === is not neccessary since you know that $_GET['konami'] is string.
Note that I turn off the E_NOTICE which someone may not like - but these type of "notices" are normally fine in many programming languages and you won't miss anything if you disable them. If you don't, you have to make your code unecessarily complex like this:
if (isset($_GET['konami']) && $_GET['konami'] == "true")
Do you really want to complicate your code with this, or rather make it simple and ignore the notices like Undefinex index? It's up to you.
Problems with other answers as you mentioned:
#Jan Hancic answer: it tests for true, not "true".
#Cameron answer: might be simplified and he didn't mention the necessity of disabling E_NOTICE.
#Frits van Campen's answer: too complex to my taste, unnecessary test for === true
Umm this?
if (isset($_GET['konami']) === true) {
// something
} else {
//show 404
}
Easy:
if(isset($_GET['konami']) && $_GET['konami'] != 'false') {
//something
} else {
// 404
}
quick and simple.
$konami = filter_input(INPUT_GET, 'konami', FILTER_VALIDATE_BOOLEAN) or die();
ref:
filter flags
filter_input
You may try this code. In this code checked two conditions by one if condition that is $konami contains value and $konami contains 'true'.
$konami = $_GET['konami'];
if( ($konami) && ($konami == "true")){
/*enter you true statement code */
}else {
/* enter your false statement code */
}
You can do it like this:
$konami = false;
if(isset($_GET['konami'])){
$konami = $_GET['konami'];
}
if($konami == "true"){
echo 'Hello World!';
}
else{
header('HTTP/1.0 404 Not Found');
}
In this case you'll always have $konami defined and - if set - filled with the value of your GET-parameter.
if(!$variable) {
//the variable is null
die("error, $variable is null");
}else{
//the variable is set, your code here.
$db->query("....");
}
This works best:
$konami = $_GET['konami'];
if($konami == "true")
{
echo 'Hello World!';
}
else
{
header('HTTP/1.0 404 Not Found');
}
Easiest and shortest way of doing it:
if($konami != null){ echo $konami; } else { header('HTTP/1.0 404 Not Found'); }

Categories