What is the logic behind the isset() function in PHP? [duplicate] - php

This question already has answers here:
pass an argument that may not be set to a function, without throwing a notice
(3 answers)
Why check both isset() and !empty()
(10 answers)
Closed 4 years ago.
I accidentally experience this issue when I was writing code in one of my application.
$ar = [
'first' => 1,
'second' => 2,
......
];
when I tried to check that index in $array which doesn't exist
if(isset($ar['third']) && !empty($ar['third'])){
echo "Found";
}else{
echo "Not Found";
}
It worked without error as expected, but when I put this conditions in the common function and then checked
function sanitize($value){
if(isset($value) && !empty($value)){
return true;
}else{
return false;
}
}
if(sanitize($ar['third'])){
echo "Found";
}else{
echo "Not Found";
}
Above sample throws an exception undefined index error, can someone explain why this is causing the error.

$value is always set because it is declared as a function parameter so it always exists. So in this case using isset() is pointless.
function sanitize($value){ // <-- Variable is declared so it exists
// within the scope of this function

You are trying to refer to the $ar array at that the 'third' index before the isset/empty check is actually executed (as that is within the sanitise function).
PHP is therefore showing the error for the if(sanitize($ar['third'])){ line.

Related

I'm comparing user input with MySQL database but I'm getting wrong result [duplicate]

This question already has answers here:
Compare variables PHP
(5 answers)
Closed 1 year ago.
I'm writing a code to compare user input with the database. I want the code display "is phishing" when the user input a word that already exist on the database.
<?php
include 'backend.php';
$userinput = $_POST['userinput'];
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
if($userinput==isset($row['keywords']))
{
echo "is phishing";
}else{
echo "is legitimate";
}
}
?>
dont use isset function, it returns true/false, you are compairing a variable to a boolean value, if that data coming from data that means it already set, just remove isset function
The isset() function returns a boolean value that indicates if the parameter you provided is set or not. i.e. The parameter is not null or declared and never initialized.
To search for a value in an array you need to use the in_array() function, as described here. Therefore your code should be:
if(in_array($userinput, $row['keywords']))
{
echo "is phishing";
}else{
echo "is legitimate";
}
Be aware that in_array() IS case-sensitive. In that case:
$values = ["StackOverflow"];
in_array("StackOverflow", $values); //true
in_array("stackoverflow", $values); //false

PHP in_array() returning false always [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
I'm trying to check if a value is in a array but it's always returning false. I've tried to fix this in quite a few different ways but none worked.
I have this file which I used require_once '../path/'; to add it to my current script. It is a JSON that was converted to PHP nested arrays.
This is the function that is always returning false. I did a lot of testing using echo and everything looks fine with $states_json and the array $cities.
If anyone could help me with this situation I would be apprciated.
EDIT: I'm calling this function with validateInstCity("RS", "Porto Alegre") so it was supposed to return true. After some more testing, I found out that the problem is that $states_json is NULL within the function. The strange part is that I used it inside others functions before without any problems. As you may see on the file, when using validateInstCity("RS", "Porto Alegre") $idx should be 22 and the function should return true.
function validateInstCity($inst_province = null, $inst_city = null) {
if (empty($inst_province) ||
empty($inst_city)) {
}
$idx;
for ($i=0; $i < count($states_json); $i++) {
if ($states_json[$i]['sigla'] == $inst_province) {
$idx = $i;
break;
}
}
$cities= array();
for ($i=0; $i < count($states_json[$idx]['cidades']); $i++) {
array_push($cities, $states_json[$idx]['cidades'][$i]);
}
if (in_array($inst_city, $cities, false)) {
return true;
} else {
return false;
}
}

Is this (isset() && !empty()) function redundant? [duplicate]

This question already has answers here:
Why check both isset() and !empty()
(10 answers)
Closed 4 years ago.
<?php
function isset_n_empty($var) {
if (isset($var) && !empty($var)){
return true;
}
return false;
}
echo isset_n_empty($x ?? null);
?>
my function is supposed to do the simple if (isset() && !empty()) logic and i used $x ?? null because if it is not used it would give me this error for undefined variables as the example
E_NOTICE : type 8 -- Undefined variable: x -- at line z
is it redundant or well-optimized?
A variable that isn't set is considered empty by empty().
Therefore, if the variable is not set, it is also empty.
Your code could be shortened by using:
echo !empty($x);
I suppose that makes the answer to your question yes.
yes, the isset is redundant. if it's !empty(), then isset() always returns true.
No the function is not redundant. It tells you if your variable is set but also falsey. There's nothing wrong with it.
On the other hand it seems like something that shouldn't really require a function of it's own. Instead of:
echo isset_n_empty($x ?? null);
You can just do:
echo isset($x) && !$x;
It's less code and doesn't require a function.
I hope this will help:
function isset_not_empty($var){
if(!isset($var))
return false;
else
return (!empty($var))
}

Is there a function like in_array that will check for empty values in PHP? [duplicate]

This question already has answers here:
PHP in_array() / array_search() odd behaviour
(2 answers)
Closed 6 years ago.
It is known that in_array() function can be used to check if an array contains a certain value. However, when an array contains the value 0, an empty or null values pass the test, too.
For example
<?php
$testing = null;
$another_testing = 0;
if ( in_array($testing, [0,1,5,6,7]) )
echo "Found";
else
echo "Not Found";
echo "<br>";
if ( in_array($another_testing, [0,1,5,6,7]) )
echo "Found";
else
echo "Not Found";
?>
In both cases "Found" is printed. But I would like the first case to print "Not Found", and the second case - "Found".
I know I can solve the problem by adding an extra if statement, or by writing my own function, but I want to know if there are any built-ins in PHP that can perform the checks.
This behavior is explained by the fact that null == 0. But null !== 0. In other words, you should check for the types as well.
You don't need another function. Simply pass true as the third parameter:
in_array($testing, [0,1,5,6,7], true)
In this case in_array() will also check the types.

custom function that uses isset() returning undefined variables when used [duplicate]

This question already has answers here:
PHP take string and check if that string exists as a variable
(3 answers)
Closed 8 years ago.
I have a field that depends has custom text if a certain condition is met...and if it isn't the field is blank.
I have written a custom function test if a variable is set
function AmISet($fieldName) {
if (isset($fieldName)) {
echo "I am set";
}else{
echo "I am not set";
}
};
but when I attach it the field I get an error that the variable is undefined. But when I do a regular isset($fieldName);
I don't have a problem. Is there any way to get around this and have my function do this instead of the isset()?
I want to add other logic in the function but I only want it to work if the variable is set...but I don't want the undefined error if it is not.
I am new to php and really appreciate any help or direction you can give me.
Thank you for the help!
You need to pass the variable by reference:
function AmISet(&$fieldName) {
if (isset($fieldName)) {
echo "I am set\n";
} else {
echo "I am not set\n";
}
}
Test cases:
$fieldName = 'foo';
AmISet($fieldName); // I am set
unset($fieldName);
AmISet($fieldName); // I am not set
However, this function is not useful as it is, because it will only output a string. You can create a function that accepts a variable and return if it exists (from this post):
function issetor(&$var, $default = false) {
return isset($var) ? $var : $default;
}
Now it can be used like so:
echo issetor($fieldName); // If $fieldName exists, it will be printed
the $fieldName comes from a query that is performed when a checkbox
is checked. If the box is checked the query is made and the variable
is set from the query, if not it doesn't exist and the field is blank.
Filter functions are designed for this kind of tasks:
<input type="foo" value="1">
$foo = filter_input(INPUT_POST, 'foo')==='1';
(There's also a specific FILTER_VALIDATE_BOOLEAN filter you can pass as second argument.)
And now you have a pure PHP boolean that always exists.

Categories