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"
Related
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;
}
This question already has answers here:
Why check both isset() and !empty()
(10 answers)
Closed 12 months ago.
When coding php I try to avoid as many warnings as possible. There is one question that bugs me for quite some time now, regarding arrays.
When working with arrays and their values I often check for empty values first before I go to the "real work".
if(array_key_exists('bla', $array){
if( !empty($array['bla']) {
# do something
}
}
My Question is:
This is a lot of code for just checking if I have values to work with. Is there some shorter way to check a value within an array that may or may not exist?
Don't use empty unless you are sure that's what you want:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
The manual doesn't explicitly list the "if var doesn't exist" cases, but here are a couple:
$array['undeclaredKey'] (an existing array, but key not declared)
$undeclaredVar; (a variable not declared)
Usually the array_key_exists check should suffice.
If you are checking for a non-empty value, then you can just use !empty($array['bla']).
You can also use isset($array['bla']), which returns false when: 1) key is not defined OR 2) if the value stored for the key is null. The only foolproof way to check if the array contains a key (even if its value is null) is to use array_key_exists().
The call to empty() is safe even if the key exists (behaves like isset()), so you don't have to protect it by the array_key_exists().
I am surprised this was not mentioned, but the shortest way fetch a value for a key without generating a warning/error is using the Error Control Operator:
// safely fetch from array, will return NULL when key doesn't exist
$value = #$array['bla'];
This allows you get the value for any key with the possibilty of its return value being null if the key does not exist.
You can simply do
if (!empty($array['bla']) {
# do something
}
I use that all the time in drupal and is good way to check if is available and avoid any kind of warnings.
Just do:
if (!empty($array['bla'])) {
There will be no warning if the key doesn't exist.
Not sure why no one mentioned isset yet, but you could do something like this:
// Before
if(array_key_exists('bla', $array){
if( !empty($array['bla']) {
// After (if element of array is scalar)
// Avoids warning and allows for values such as 0
if ((true === isset($array['bla'])) && (mb_strlen($array['bla']) > 0)) {
// After (if element of array is another array
// Avoids warning and ensures element is populated
if ((true === isset($array['bla'])) && (count($array['bla']) > 0)) {
If you really want to get crazy with a better way of checking vars, you could create a standardized API, below are a few methods I created to avoid laundry list function calls for variable checking:
class MyString
{
public static function populated($string)
{
//-----
// Handle various datatypes
//-----
// Don't want to assume an array as a string, even if we serialize then check
if (is_array($string)) {
return false;
}
if (is_object($string)) {
if (!is_callable(array($string, '__toString'))) {
return false;
}
$string = (string) $string;
}
//-----
return (mb_strlen($string) > 0) ? true : false;
}
}
class MyArray
{
public static function populatedKey($key, $array, $specificValue = null, $strict = true)
{
if ((is_array($array)) &&
(array_key_exists($key, $array))) {
if (is_array($array[$key])) {
return (count($array[$key]) > 0) ? true : false;
}
elseif (is_object($array[$key])) {
return true;
}
elseif (mb_strlen($array[$key]) > 0) {
if (!is_null($specificValue)) {
if ($strict === true) {
return ($array[$key] === $specificValue) ? true : false;
} else {
return ($array[$key] == $specificValue) ? true : false;
}
}
return true;
}
}
return false;
}
}
// Now you can simplify calls
if (true === MyArray::populatedKey('bla', $array)) { // Do stuff }
if (true === MyString::populated($someString)) { // Do stuff }
There are 1K ways to skin a cat, but standardizing calls like this increase Rapid Application Development (RAD) quite a bit, keeps the calling code clean, and helps with self documentation (semantically logical).
I wrote a small function to check the required fields of a form, are not empty.
The function accepts two arguments, 1st is an array with all values from $_POST superglobal.
2nd is the required fields array which I populate.
Have a look:
public $errors = array();
public function validate_fields($fields_array, $required_fields)
{
foreach ($required_fields as $key => $value)
{
if (array_key_exists($key, $fields_array))
{
# If key exists in $fields_array
# check that the key value inside $fields_array is set & isn't empty
# if it's empty, populate with an error
if(empty($fields_array[$key][$value]))
{
$this->errors[] = "{$key} is empty but in fields_array";
}
}
else
{
# Key does not exists in $fields_array
# Did someone temper with my html ?
$this->errors[] = "{$key} is not in fields_array";
}
}
return (empty($this->errors)) ? true : false;
}
The issue I'm having seems to be related to "if(empty($fields_array[$key][$value]))"
statement. my goal is to check that $fields_array key value is not empty based on $required_fields key. I'm sure the statement I'm using is off. If you see anything that you think can be written better, please let me know, as I am new to php. Appreciate the help.
I think what you're trying to do is:
if(empty($fields_array[$key])) {
//this means value does not exist or is FALSE
}
If you also want to check for empty-strings or white-space only, then you need something more than just empty. E.g.
if(empty($fields_array[$key]) || !trim($fields_array[$key])) {
//this means key exists but value is null or empty string or whitespace only
}
Do note that the above answers will only work for indexed arrays in >PHP 5.4. If you have an associative array you have to use isset instead of empty:
if(isset($fields_array[$key]) && trim($fields_array[$key]) != '')
See http://nl3.php.net/manual/en/function.empty.php, example #2
You don't need to select the value as an index just key. Where $fields_array[$key] = $value;
if(empty($fields_array[$key]) && trim($fields_array[$key]) != '')
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);
Im currently testing a simple PHP function.
I want to to return the currently value of a field if the function is called without any parameter passed or set a new value if a parameter is passed.
Strange thing is: if I pass 0 (var_dump is showing correct value int(1) 0), the function goes into the if branch like i called the function without any value and i just don't get why.
function:
public function u_strasse($u_strasse = 'asdjfklhqwef'){
if($u_strasse == 'asdjfklhqwef'){
return $this->u_strasse;
} else {
// set new value here
}
}
either u_strasse() or u_strasse(0) gets me in the if branch.
You should use null as the default value:
public function u_strasse($u_strasse = null)
{
if ($u_strasse === null) { $u_strasse = 'asdjfklhqwef'; }
// rest of function
}
When comparing variables of different types (specifically strings and numbers), both values will be converted to a number. Therefore, your 'asdjfklhqwef' converts to 0 (number), the comparison is true.
http://www.php.net/manual/en/language.operators.comparison.php
Use === instead of ==:
public function u_strasse($u_strasse = 'asdjfklhqwef'){
if($u_strasse === 'asdjfklhqwef'){
return $this->u_strasse;
} else {
// set new value here
}
}
In case of == php tries to convert 'asdjfklhqwef' to number (because you pass $u_strasse as a number) and (int)'asdjfklhqwef' equals 0. To avoid this behavior you need to compare strictly (===)
Read more about difference in == and === here
Pass '0' instead of 0. The former will be a string.
You can cast it like this:
$myvar = 0;
u_strasse((string)$myvar);