Class Exists Check Comparison - php

Is there a diference between this comparisons ?
What is the diference between ! and === FALSE ?
if (!class_exists($class)) {
require($class.'.php');
}
if (class_exists($class) === FALSE) {
require($class.'.php');
}

In this case, no.
Some people think it's good programming style to explicitly show that they're comparing to a boolean. Personally... I don't like it, but I guess the more verbose form is more obvious, as the ! operator isnt the mose visible thing when smashed between a parenthesis and other vertically'ish characters.

Yes both are the different things:
php automatically considers 0 as "false" and 1 as "true" so when ever you use function response directly inside the if condition at that this both makes a difference.
consider a function, if executed properly at that it returns int number. it may be 0 too.
But if function did not match requirement at that it is returning false.
So at this time function returning value 0 is success. event though the result is zero. At this if you check this in if condition like
$return = someFunction();
if($return){
//code if ture
}
so if $return is 0 your if code will not be executed even your function execution was correct so in that case you should check like
$return = someFunction();
if($return !== FALSE){
//code if ture
}
=== and !== are used to check the response exactly match return type also.
if('0' === 0)
will return false
but
if('0' == 0)
will return true...
Hope your idea is clear now.
check this out:
if('0' == 0){
echo 'Hi, I will be in screen :)';
}
if('0' === 0){
echo 'I will not be in screen :(';
}

Related

StrPos always returns False?

I've been working on a very basic search engine. It basically operates by checking if the word exists. If it does, it returns the link. I know most of you would suggest to create a database from phpMyAdmin but I don't remember the password to make the mySql_Connect command work.
Anyway here is the code:
<?php
session_start();
$searchInput = $_POST['search'];
var_dump($inputPage1);
var_dump($searchÄ°nput);
$inputPage1 = $_SESSION['pOneText'];
$inputPage2 = isset($_SESSION['pTwoText']) ? $_SESSION['pTwoText'] : "";
$inputPage3 = isset($_SESSION['pThreeText']) ? $_SESSION['pThreeText'] : "";
if (strpos($inputPage1, $searchInput)) {
echo "True";
} else {
echo "False";
}
?>
When I search a word, any word from any page, weather it exists or not, it always returns false. Does anyone know why?
From the PHP documentation:
Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So the function returns the integer 0 since $searchInput starts at the first character of $inputPage1. Since it is inside an if condition, that expects a boolean, the integer is then converted to one. When converted to boolean, zero is equal to false so instead the else block is executed.
To fix it, you need to use the !== operator (the not equal equivalent of ===):
if (strpos($inputPage1, $searchInput) !== false) {
//...
Try stripos() to match case insensitive
First print all items in $_POST and $_SESSION using
echo "<pre>";
print_r($_POST);
print_r($_SESSION);
and ensure that the search string really exist in the bigger string .
Also make sure that your are using "false" to compare :
i.e
$pos = strpos($biggerString,$seachString);
if($pos !== false)
{
echo "Not found";
}

How do i search an array in php and return true if it finds one of my variable?

if (array_search($soca, $user_socs))
I know that this will search the array by inputing a variable and an array but i was wondering if it is possible to make it return true, because since it doesn't return true, my if statement is not being carried out.
References
array_search documentation
You need to code this function to expect a return of FALSE if it does not find what you are looking for.
So
if (array_search($soca, $user_socs) !== false) {
// then I found something
// not sure what but its defintely not
// returning a failed to find situation
} else {
// I did not find anything
}
Note the use of the !== and NOT != this is expressly for situations where a function can return actual data that might equate to false but not actually be false i.e. where it may return the 0'th occurance its a valid occurance which may be confused with false if you just us ==.
if (($key = array_search($soca, $user_socs)) !== FALSE) {
...
}

Understanding php logic on conditionals - return true understanding

The point is to validate, only when,
$this->data[$this->alias]['enabled']
It's equal to one. So, if $this->data[$this->alias]['enabled'] == 1, validate.
I was expecting that this peace of code, would do the job:
public function compareDates() {
if ($this->data[$this->alias]['enabled'] == 1) {
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}
}
However it seems that that doesn't work as I expected. Instead, it gets always validated, regardless the value of $this->data[$this->alias]['enabled']
This code, however, seems to do the job just fine:
public function compareDates() {
if ($this->data[$this->alias]['enabled'] != 1) return true; // we don't want to check
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}
What is, in your understanding, the meaning of "we don't want to check"?
Why: if ($this->data[$this->alias]['enabled'] == 1) is not enough?
Can anyone care to explain?
Update:
If I do:
public function compareDates()
{
if ($this->data[$this->alias]['enabled'] === "1") {
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
} else {
return true;
}
}
It works as well. My question is:
Why do I need to explicitly declare the return true?;
You're doing a simple comparison (==) so PHP is looking for "truthy" statements. So ANY value that is not "falsey" will evaluate your statement (i.e. 0, false, empty strings, NULL). You can find a complete list here.
The best way around this is to use equivalency to ensure it's the exact value you want
if ($this->data[$this->alias]['enabled'] === 1)
That will force PHP to look for an integer of 1. Be aware, though, that your value MUST be the same. In other words
if('1' === 1)
Is always false because string 1 is not the same as integer 1

Explanation for very odd php function return

So my code in the past needed a variable to run through 2 functions and then return the value as such.
function 1($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
// pass the return to next function
function 2($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
On the next check it returns a message to the user as such:
if($variable == -1) // display message
if($variable == -2) // display message
if($variable == true) // display message
Now, per requirement of work the variable must go through a 3rd function check still returning a -1, -2 or true and then go onto the final if statements for display.
Now this is where it gets odd. If I keep it at 2 functions the if statements work, however if I run it through the 3rd check function I need to format my if's like this in order to correctly check the return:
if($variable === -1) // display message
if($variable === -2) // display message
if($variable === true) // display message
Notice I have to add the 3rd '=' symbol. I just can't figure out why this is happening. Is this normal by some PHP law I don't know about or is this a bug?
This is not odd behavior, it's very natural for PHP.
Following expression:
if ($variable == true) {
}
means that PHP will cast left operand to less pretensive type(in this case BOOLEAN) and do comparison after this. Which obviously will result in TRUE if $variable value is not 0 or FALSE or NULL or ''
In second case i.e. === there is strict check value and type of both operands are compared.
The triple equals sign (===) only returns true if the two objects being compared are identical (of the same type and value), not just equal.
For example:
$a = 1;
$b = "1";
echo $a == $b; // True
echo $a === $b; // False
Your code does not show how you call the functions and store returns, there may be a problem. Plus, I suppose you called function 1 and 2 only for illustration because as you know you cant start name of the function with a number.
=== is 'equals exactly' (value and type). Often used for logical tests, because sometimes you need to distinguish 0 from false and 1 from true.

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