Check if the variable passed as an argument is set - php

I want to check if a variable called $smth is blank (I mean empty space), and I also want to check if it is set using the function I defined below:
function is_blank($var){
$var = trim($var);
if( $var == '' ){
return true;
} else {
return false;
}
}
The problem is I can't find a way to check if variable $smth is set inside is_blank() function. The following code solves my problem but uses two functions:
if( !isset($smth) || is_blank($smth) ){
// code;
}
If I use an undeclared variable as an argument for a function it says:
if( is_blank($smth) ){
//code;
}
Undefined variable: smth in D:\Www\www\project\code.php on line 41
Do you have a solution for this?
Solution
This is what I came up with:
function is_blank(&$var){
if( !isset($var) ){
return true;
} else {
if( is_string($var) && trim($var) == '' ){
return true;
} else {
return false;
}
}
}
and works like a charm. Thank you very much for the idea, NikiC.

Simply pass by reference and then do isset check:
function is_blank(&$var){
return !isset($var) || trim($var) == '';
}

Whenever you use a variable outside of empty and isset it will be checked if it was set before. So your solution with isset is correct and you cant' defer the check into the is_blank function. If you only want to check if the variable is empty, use just the empty function instead. But if you want to specifically check for an empty string after a trim operation, use isset + your is_blank function.

Use empty. It checks whether the variable is either 0, empty, or not set at all.
if(empty($smth))
{
//code;
}

Related

PHP - Custom validator function and passing unset variable

I have a custom validator function which checks different properties of a passed variable including if the variable isset(). However if the variable is not set, the warning is thrown when I call the validator function. The warnings are not displayed and the script runs without a hitch, but I don't want my error log cluttered with all of these entries.
The easy solution is to prefix all of the calls to the function with #, but I'd rather not for obvious reasons. Alternatively I could remove the isset() from the function (or leave it I guess) and instead place the isset() check along side the function call.
I can't see these being the only options; How else can I perform the isset() within the validator function while preventing these warnings from being logged. I'd like to still have undefined variables warnings logged overall, just not when calling this function.
Here is the function:
function validate_data($value, $required = false, $min = false, $max = false, $numeric = false, $email = false){
if($required === true && (!isset($value) || strlen(trim($value)) < 1) ){
return false;
}
if($min !== false && strlen(trim($value)) < $min){
return false;
}
if($max !== false && strlen(trim($value)) > $max){
return false;
}
if(strlen(trim($value)) > 0 && $numeric === true && (!is_numeric(trim($value)))){
return false;
}
if(strlen(trim($value)) > 0 && $email === true && !filter_var(trim($value), FILTER_VALIDATE_EMAIL)){
return false;
}
return true;
}//validate_data()
Here is an example call:
if(!$someClassName->validate_data($var, true, false, false, false, false)){
//Do some stuff
}
isset() and empty() are special functions which accept undefined variables without a warning. You cannot create your own function which accepts this.
But if you work with an undefined variable, you have probably other problems to deal with. Even if not needed in php it is good practise to initialize all variables. A (bad) workaround might be something like this:
if (!isset($var)) $var = null;

isset() and empty() do not seem to fix the "undefined index" notice

The company keeps their PHP errors suppressed in code, but I turned it on to see why something of mine was not working.
Now, however, I am getting hundreds of Undefined index messages that I would like to turn off so that I can find the messages from MY code.
Here is one particular block that gives many errors:
final public function getAttribute($name) {
$value = '';
if(is_array($this->attributes[$name]) === false) { // Notice: Undefined index: name
$value = trim($this->attributes[$name]);
} else {
$value = trim(implode(' ', $this->attributes[$name]));
}
return $value;
}
To eliminate these notices, I followed the post Why check both isset() and !empty() to write it like this:
final public function getAttribute($name='') {
if (!isset($name) || empty($name)) {
return '';
}
$value = '';
if(is_array($this->attributes[$name]) === false) { // Notice: Undefined index: name
$value = trim($this->attributes[$name]);
} else {
$value = trim(implode(' ', $this->attributes[$name]));
}
return $value;
}
I still get the notices, and in the same place.
How do I fix the code so that it does not create this condition?
You are not using the right variable to check against. You need to check for whether the index of the array exists.
final public function getAttribute($name='') {
if (!isset($this->attributes[$name]) || empty($this->attributes[$name])) {
return '';
}
// ...
}
try isset($this->attributes[$name]) in your second block
This will not throw undefined index:
[...]
if (isset($this->attributes[$name])) {
// The key $name is set in $this->attributes
}
else {
// The key is not set
}
if (!isset($this->attributes[$name])) {
return NULL;
}
The above code should do it.
Use empty first, because isset will throw undefined error if the index doesn't exist, and empty will never do, like:
if (empty($name) && !isset($name)) {
return '';
}
Using AND here will prevent returning if the value is already set but equals to '', o or false.
If you want to return if the value is true, some string or value, just use empty. Not need to use isset.

How to write a function that checks if a variable is defined and is a number?

In the past when I needed to check if a variable was set and also a number, I would do:
if( isset($_GET['var']) && is_numeric($_GET['var']) )
But I think that's kind of ugly, especially when I need to check a bunch of variables in the same if statement, so I made a function:
function setAndNum($var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
The problem is that when I pass an undefined variable to the function, like this (supposing the variable in the GET array is undefined):
if( setAndNum($_GET['var']) )
I get the php error:
Notice: Undefined index: ...
So the whole purpose of the function is basically defeated (or half the purpose, at least ;) ).
One thing that confuses me is how the isset() function works, and why I can pass an undefined variable to it but not to my own function?
Is it possible to make my setAndNum() function work?
Your problem is with $_GET being an array. When you pass $_GET['var'] to your function, this array value is already looked up and used as an argument to the function. Therefore you cannot effectively check the presence of 'var' in $_GET from within this function. You could rewrite it a bit to make it work for array values, something like this:
function setAndNum($key, $array)
{
if(array_key_exists($key, $array) && is_numeric($array[$key]))
return 1;
else
return 0;
}
Then call it like this:
if( setAndNum('var', $_GET) )
It's good practice to verify a key exists before using it:
if (array_key_exists($_GET, 'var')) {
// do stuff with $_GET['var']
}
function setAndNum(&$var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
Please, try using this version:
function setAndNum(&$var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
You can use the # operator to prevent error reporting:
setAndNum(#$_GET['var']);
This way, the error message of the non-existant index will not be printed, and the return value will be 0.
You could also write two functions, one that checks for an array and one that checks for normal variable
function setAndNum($var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
function setAndNumArray($array, $key)
{
if(isset($array) && isset($array[$key]) && is_numeric($array[$key]))
return 1;
else
return 0;
}
if you are using variables from GET or POST method you may do like this as these are super globals.
function setAndNum()
{
if(isset($_GET['var']) && is_numeric($_GET['var']))
return 1;
else
return 0;
}
now coming to your another query. isset checks whether a variable is s et or not like
if(isset($_POST['submit']))
{
// any code under button click
}

PHP get ? without setting variable to anything

If I were to call:
www.*.com?hello
if($_GET["hello"]){
}
It will always return false because ?hello variable needs to be set as something...
Is there a way to get the ? part without setting the variable to anythign before hand?
You can check if variable is set like this:
if(isset($_GET["hello"])){
}
sometimes key_exists() is better because if $_GET["hello"] == null you can get false
if (key_exists("hello", $_GET)) {
}
$_GET["hello"] is falsy, check if it's set at all
if (isset($_GET["hello"])) {
//do stuff
}
Use array_key_exists:
if (array_key_exists("hello", $_GET)) {
}
Please read this for a difference between isset and array_key_exists.
The usual way is to check it like:
if(isset($_GET["hello"]) && $_GET["hello"] != ""){
//code
}
if(!empty($_GET["hello"]))
{
}
Instead of checking for both isset and $_GET != "".

PHP referencing array element (&$array['element']) creates element

I have a function that checks if a variable is exists.
function variable( &$var, $default = NULL )
{
if( (!isset($var) && !is_array($var)) || empty($var) )
{
return FALSE;
}
elseif( is_array($var) && count($var) <= 0 )
{
return FALSE;
}
else
{
return $var;
}
}
My problem is, that this function creates an array when I pass an array element reference like $array['element'] the array $array and the index 'element' is created even if it did not exists before.
What the function is supposed to do is having something like echo variable($var); which does no produce an error even if $var is not defined.
Is there a way to delete this again or even better not let the function create the array?
Thanks.
See here: http://ch.php.net/manual/de/function.array-key-exists.php
array_key_exists is the "key", no pun intended :-)
like so:
if (array_key_exists('element', $array)({
// do the fan dango
}
To delete, you can use unset($array['element']); or unset($array); depending on your goal.
For making sure the array turns into a string, just use implode("",$array);

Categories