If I were to create this variable:
$example = $_GET['test'];
I would get this error message if $_GET['test'] is not set:
Notice: Undefined variable...
How can I create variables like this (without having to use if statements and the like) without having to see this error message?
$example = isset($_GET['test']) ? $_GET['test'] : NULL;
Typically, I do something like the following:
function get($key, $default = null) {
return isset($_GET[$key]) ? trim($_GET[$key]) : $default;
}
$example = get('test');
Related
Here is the function:
function is_set($var, $placeholder = null){
if(isset($var)){
return $var;
} else {
return $placeholder;
}
}
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
is_set($_POST['freq'], '');
}
It returns "Notice: Undefined index: freq in... "
While this code works well:
echo isset($_POST['freq']) ? $_POST['freq'] : '';
Why is that??
First print_r($_POST);and check variable you trying to access is available.
you are tryin g to pass $_POST['freq']) for the validation before checking whether the variable exists.
exception triggers when your execution hits is_set($_POST['freq']); without poast parameter 'freq' .
Try some thing like
if(!empty($_POST['freq'])){
is_set($_POST['freq']);
}
or pass whole $_POST to is_set function and validate variable there.
What I'm trying to do is write one function to reuse vs writing out an if statement every time.
If statement:
if (!isset($value)){ echo 'null';}else{ echo $value;}
Function:
function isSetTest($value){
if ( !isset($value)){
$value = NULL;
}
return $value;
}
echo'name'.isSetTest($value);
Function works but I still get the "undefined" error message which is what i'm trying to avoid.
Pass by reference instead, so that no processing of the variable is done until you want it:
function isSetTest(&$value) { // note the &
if (!isset($value)) {
$value = NULL;
}
return $value;
}
You can shorten this a bit:
function isSetTest(&$value) {
return isset($value) ? $value : null;
}
I have a function that does something similar, except you can provide an optional default value in the case that the variable is not set:
function isset_or(&$value, $default = null) {
return isset($value) ? $value : $default;
}
The problem in your code is, that you still pass an undefined variable to your function, so that's why you still get your undefined error.
One way to solve this now, is that you pass your variable name as a string and then use variable variables, to check if it exists, e.g.
function isSetTest($value){
global $$value;
if ( !isset($$value)){
$$value = NULL;
}
return $$value;
}
echo'name'.isSetTest("value");
Demo
I have the following code in numerous places (thousands of places) around my project:
$foo = isset($mixed) ? $mixed : null;
Where $mixed can be anything: array, array element, object, object property, scalar, etc. For example:
$foo = isset($array['element']) ? $array['element'] : null;
$foo = isset($nestedArray['element']['key']) ? $nestedArray['element']['key'] : null;
$foo = isset($object->prop) ? $object->prop : null;
$foo = isset($object->chain->of->props) ? $object->chain->of->props : null;
Is there a way to write this repeated logic as a (simple) function? For example, I tried:
function myIsset($mixed)
{
return isset($mixed) ? $mixed : null;
}
The above function looks like it would work, but it does not in practice. For example, if $object->prop does not exist, and I call myIsset($object->prop)), then I get fatal error: Undefined property: Object::$prop before the function has even been called.
Any ideas on how I would write such a function? Is it even possible?
I realize some solutions were posted here and here, but those solutions are for arrays only.
PHP 7 has a new "Null coalescing operator" which does exactly this. It is a double ?? such as:
$foo = $mixed ?? null;
See http://php.net/manual/en/migration70.new-features.php
I stumbled across the answer to my own question while reading about php references. My solution is as follows:
function issetValueNull(&$mixed)
{
return (isset($mixed)) ? $mixed : null;
}
Calls to this function now look like:
$foo = issetValueNull($array['element']);
$foo = issetValueNull($nestedArray['element']['key']);
$foo = issetValueNull($object->prop);
$foo = issetValueNull($object->chain->of->props);
Hopefully this helps anyone out there looking for a similar solution.
isset is a language construct, not a regular function. Therefore, it can take what would otherwise cause an error, and just return false.
When you call myIsset($object->prop)), the evaluation occurs and you get the error.
See http://php.net/manual/en/function.isset.php
This is the same problem as using typeof nonExistentVariable in JavaScript. typeof is a language construct and will not cause an error.
However, if you try to create a function, you get an error for trying to use an undefined variable.
function isDef(val) {
return typeof val !== 'undefined';
}
console.log( typeof nonExistent !== 'undefined'); // This is OK, returns false
isDef(nonExistent); // Error nonExistent is not defined
You could actually just write it like:
$foo = $mixed?:null;
If you just want to check if it exist do this
function myIsset($mixed)
{
return isset($mixed); // this is a boolean so it will return true or false
}
function f(&$v)
{
$r = null;
if (isset($v)) {
$r = $v;
}
return $r;
}
I get a lot of array from some API and I need to check weither some variable exist or not.
I have a lot of block that look like that :
if (isset($var))
$varToSet = $var;
else
$varToSet = '';
So I've decided to make a function for that. I came with that:
function setVar($var)
{
if (isset($var))
return $var;
return '';
}
But as I would expected I got the error Undefined variable, I figured out I needed to passe the argument by reference so I would get the following prototype :
function setVar(&$var);
And It was working perfectly until now, here's an example of my problem :
// works fine
$var = "test";
$varToSet = setVar($var);
// works fine
$var = "test";
$varToSet = setVar($doesNotExist);
// works fine
$var = "test";
$varToSet = setVar($doesNotExist['index']);
// doesn't work
$var = "test";
$varToSet = setVar($var['index']);
In the last example I get Illegal string offset 'index and Only variables can be passed by reference PHP errors.
I know why I got those errors, I just can't figure out how overcome this problem.
i mainly use property_exists to check if a value exist on a json object.
function getFromJson($json,$value)
{
if (property_exists(json, $value)) {
return $json->$value;
}
return null;
}
function get($var,$value = null)
{
if (is_null($value)) {
return $var;
}
if (is_object($var) && property_exists($var, $value)) {
return $json->$value;
}
if (is_array($var)) {
return $var[$value];
}
return $var;
}
The error gives you the answer. Your variable is a string. But you are trying to access an array element by using brackets [ ].
And the second is caused by invalid refference.
This is passing by reference:
$variable = 'test';
myFunction($variable);
and this is passing by value:
myFunction('test');
That's a big difference!
You can't call string as array
$varToSet = setVar($var['index']);
You can change the line to:
echo $var['index'];
and you will still have the same error/warning.
If you want to validate if array variable is set use
isset($var['index'])
but it returns value, not a refference
i'm in need of a php function whose first argument will check that the variable exist or not outside of the function, if variable exist then echo it's value and if the variable doesn't exist then echo a default value for the variable given in second argument of the function. and in last remove(delete) both the variable passed to the function just after echoing their values.
simply :
function if_exists ($argument, $default)
{
// if $argument exist then echo it's value and then remove $argument variable.
// if the $argument doesn't exist then echo it's $default value and then remove $default variable.
}
i will use it like this :
$any_variable
if_exists ($any_variable, 'this variable is not defined');
this code is not doing the perfect job for me :
function if_exist(&$argument, $default = '')
{
if (isset ($argument))
{
echo $argument;
}
else
{
echo $default;
unset ($default);
}
}
thanks.
You don't need a function for this
$var = isset($var) ? $var : $default;