php, key check on NULL variable gets set, how to? - php

here is my example:
$data = null;
var_dump($data); // returns null
is($data['test']);
var_dump($data); // returns array (size=1)
// 'test' => null
function is(&$var, $default = null)
{
return isset($var) ? $var : $default;
}
notice that after I run is($data['test']), $data becomes $data['test'] = null
any ideas why this behavior?
I am looking to get null. I am running php 7
edit: it's the & symbol, just not sure why would yield that result

You cannot pass a variable with a non existing key to a function (even with reference) since the value will be passed to the function.
If we have $data and in the next line if we do $data['test'], the $data variable will be updated to an array.
So in your case, when you use is($data['test']);, it updates the variable.
Then it goes to the function, and checks isset($var). It is already set since the variable is updated already. So the isset gets a true return. That return will contain the updated variable which is $data['test'].
I think the solution from #Fred B will work in this case.

try using array_key_exists() and return null if key not found.

This solution seems to work, though less elegant:
is($data, 'test');
var_dump($data); // returns array (size=1)
// 'test' => null
function is($var, $key, $default = null)
{
return isset($var[$key]) ? $var[$key] : $default;
}

Related

use php NULL like array

<?php
ini_set('display_errors',1);
ini_set('error_reporting',-1);
$data = null;
var_export( $data['name']);
echo PHP_EOL;
var_dump($data['name']);
Why the result is null, but no notice or warning occured?
Because null is an undefined type, $data['name'] therefore creates its own array.
If you check the data type of $data before assigning null, you will get the undefined variable notice.
echo gettype($data);
$data = null;
After you assigned null to $data, you will see NULL for its value and its data type.
$data = null;
echo gettype($data);
var_dump($data);
According to the documentation of NULL, you're getting NULL for $data['name'] means that it has not been set to any value yet.
The special NULL value represents a variable with no value. NULL is
the only possible value of type null.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
The following two examples show that the previously defined variable is not auto-converting to array, and keep its original data type.
Example 1:
$data = null; // $data is null
var_dump($data['name']); // null
var_dump($data[0]); // null
Example 2:
$data = 'far'; // $data is string
$data[0] = 'b'; // $data is still string
echo $data; // bar
Just reread documentation about type casting in php.
http://php.net/manual/en/language.types.type-juggling.php
PHP is not so strict as c/c++ or java :-)

Joomla check for empty string with JInput

Following this guide to sanitize my inputs, I'm wondering if an empty string is covered with this?
$jinput = JFactory::getApplication()->input;
$this->name = $jinput->get('name', '', 'STRING');
Typically without Joomla I'd be checking for an empty string as well. Something like:
if (!empty($_POST['name']))
Looking at the JInput get method I see that it checks if it is isset:
public function get($name, $default = null, $filter = 'cmd')
{
if (isset($this->data[$name]))
{
return $this->filter->clean($this->data[$name], $filter);
}
return $default;
}
Not the same thing, as isset will only check for null. However that is the default value for using the get method. So if I specify an empty string for the second parameter am I covered here?
$this->name = $jinput->get('name', '', 'STRING');
It's not up to Joomla to decide whether your empty string is valid value or not. They have to use isset(), because if they would use empty() and you return '0' which you would expect as normal, Joomla would return default value instead of that '0'.
So it's completely normal that they just use isset() to check if variable is set, and it's up to you to decide what values you accept.
If the value isn't set, and you set as the second parameter empty string '', you'll get an empty string returned.
In your example an empty string would be returned, which is expected behaviour.

how to store isset condition php to avoid repetition

my code:
if (isset($dayMarks[$res['resId']][$dDate])) {
$var=$dayMarks[$res['resId']][$dDate];
echo $var;
}
note that the isset condition is identical to the value assigned to $var, which creates a pretty ugly code.
How is it possible to assign the condition to $var without repeating it?
(in javascript, I'd write if (var=$dayMarks[$re...) )
This is a common problem in PHP where including files can create uncertainty about variables.
There are a two approaches that work well for me.
Default Assignment
With default assignment the $var variable will be given a default value when the key doesn't exist.
$var = isset($dayMarks[$res['resId']][$dDate]) ? $dayMarks[$res['resId']][$dDate] : false;
After this code can assume that $var will always contain a valid value.
Default Merger
My preferred method is to always declare a default array that contains all the required values, and their defaults. Using the False value to mark any keys that might be missing a value (assuming that key holds another value type besides boolean).
$default = array(
'date'=>false,
'name'=>'John Doe'
);
$dayMarks[$res['resId']] = array_merge($default, $dayMarks[$res['resId']]);
This will ensure that the required keys for that variable exist, and hold at least a default value.
You can now test if the date exists.
if($dayMarks[$res['resId']]['date'] !== false)
{
// has a date value
}
While this might not work exactly for your array. Since it looks like it's a table structure. There is a benefit to switching to named key/value pairs. As this allows you to easily assign default values to that array.
EDIT:
The actual question was if it was possible to reproduce the JavaScript code.
if (var=$dayMarks[$re...)
Yes, this can be done by using a helper function.
NOTE: This trick should only be used on non-boolean types.
function _isset($arr,$key)
{
return isset($arr[$key]) ? $arr[$key] : false;
}
$a = array('zzzz'=>'hello');
if(($b = _isset($a,'test')) !== false)
{
echo $b;
}
if(($c = _isset($a,'zzzz')) !== false)
{
echo $c;
}
See above code here
$isset = isset(...); //save the value
if ($isset) { .... }; // reuse the value
...
if ($isset) { ... }; // reuse it yet again
The only thing you can do is store $res['resId'][$dDate].
$var = $res['resId'][$dDate];
if( isset($dayMarks[$var]) ) {
$var = $dayMarks[$var];
echo $var;
}
If you only want to assign a variable processing simply, you can also write this as:
$var = $dayMarks[$res['resId']][$dDate]);
if (!isset($var)) unset($var);

Function to set default value of associative array if the key is not present

Is there a function in PHP to set default value of a variable if it is not set ?
Some inbuilt function to replace something like:
$myFruit = isset($_REQUEST['myfruit']) ? $_REQUEST['myfruit'] : "apple" ;
PHP kind of has an operator for this (since 5.3 I think) which would compress your example to:
$myFruit = $_REQUEST['myfruit'] ?: "apple";
However, I say "kind of" because it only tests if the first operand evaluates to false, and won't suppress notices if it isn't set. So if (as in your example) it might not be set then your original code is best.
The function analogous to dictionary.get is trivial:
function dget($dict, $key, $default) {
return isset($dict[$key]) ? $dict[$key] : $default;
}
For clarity, I'd still use your original code.
Edit: The userland implementation #2 of ifsetor() at http://wiki.php.net/rfc/ifsetor is a bit neater than the above function and works with non-arrays too, but has the same caveat that the default expression will always be evaluated even if it's not used:
function ifsetor(&$variable, $default = null) {
if (isset($variable)) {
$tmp = $variable;
} else {
$tmp = $default;
}
return $tmp;
}
As far as i know there exists nothing like this in PHP.
You may implement something like this yourself like
$myVar = "Using a variable as a default value!";
function myFunction($myArgument=null) {
if($myArgument===null)
$myArgument = $GLOBALS["myVar"];
echo $myArgument;
}
// Outputs "Hello World!":
myFunction("Hello World!");
// Outputs "Using a variable as a default value!":
myFunction();
// Outputs the same again:
myFunction(null);
// Outputs "Changing the variable affects the function!":
$myVar = "Changing the variable affects the function!";
myFunction();
You could also create a class implementing the ArrayAccess, which you pass 2 arrays during construction ($_REQUEST and an array with defaults) and make it choose the default value transparently.
Btw., relying on $_REQUEST is not a wise idea. See the manual on $_REQUEST for further information.
Instead of testing, if a key not exists and then return a default value, you can also fill your array with this values, before accessing it.
$expectedKeys = array('myfruit');
$requestData = array_merge (
array_combine(
$expectedKeys,
array_fill(0, count($expectedKeys), null)),
$_REQUEST);
$postData is now an array with all keys you expect (specified by $expectedKeys), but any entry, that is missing in $_REQUEST is null.
$myFruit = $requestData['myfruit'];
if (is_null($myFruit)) {
// Value not exists
}
But I also recommend to just stay with the ternary operator ?:.
There is a function called ife() in the CakePHP framework, you can find it here http://api13.cakephp.org/view_source/basics.php/, it is the last function!
You can use it like this:
echo ife($variable, $variable, 'default');

Can you describe the following PHP function?

Can anyone describe the following php function:
function get_setting_value($settings_array, $setting_name, $default_value = "")
{
return (is_array($settings_array) && isset($settings_array[$setting_name]) && strlen($settings_array[$setting_name])) ? $settings_array[$setting_name] : $default_value;
}
What does it return and whats its purpose?
This is equivalent:
function get_setting_value($settings_array, $setting_name, $default_value = "")
{
// Check that settings array really is an array
if (!is_array($settings_array)) {
return $default_value;
}
// Check that the array contains the key $setting_name
if (!isset($settings_array[$setting_name])) {
return $default_value;
}
// Check that the value of that index isn't an empty string
if (!strlen($settings_array[$setting_name])) {
return $default_value;
}
// Return the requested value
return $settings_array[$setting_name];
}
The function returns a setting value if found, or the default value (which is optional).
A more detailed answer:
if the the given settings array is an actual array
if the setting_name exists in the array
if the setting value represented by the setting name is not empty, false, or 0 then return it
else return the default value, which, if not set, is an empty string
if $settings_array is an array and the setting $setting_name (which is fournd in the settings array) has a value and the value of $setting_array[$setting_name] has a value, then return the value of $setting_array[$setting_name] otherwise return the $default value.
I guess the purpose of this is go get a particular setting and check that it exists (the settings are all in the array, they are set and the have a length) if not then return your default values.
This uses an "inline if statement"

Categories