PHP: checking key value is not empty - php

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]) != '')

Related

Transform any null input to empty string

So I've got a while loop, inside I have $array_collections that gives me 35 value per loop, I want to verify for every value if it's equal to NULL then give it an empty string. I did that :
while ($array_collections = tep_db_fetch_array($query)) {
foreach ($array_collections as $key => $value) {
if (is_null($value)) {
$array_collections[$key] = "";
}
}
$docs[] = new \Elastica\Document('', \Glam\HttpUtils::jsonEncode(
array(
'X' => $array_collections['X'],
... etc
)));
}
This technically should work, but the loop goes over 500K elements so it's huge, and for every element we put it into a table, problem is that I run out of memory at some point. So is there another simple way to give any given NULL value an empty string without looping?
well, you can put NOT NULL constraint with empty string as DEFAULT value in the DB for that so you dont need to do that in php using looping, but if you dont want to change the DB design then you can use COALESCE in your query
select COALESCE(yourfield,'') from table
it will convert NULL value into empty string
You can use array_map function to replace null values into empty string.
$array_collections=array_map(function($ar)
{
if(isset($ar) && $ar!=null){
return $ar;
}
return '';
},$array_collections);
Above code replace all null values to empty string. No need of loop.
you can use array_walk:
function replace_null(&$lsValue, $key) {
if(is_null($lsValue)) {
$lsValue = "";
}
}
array_walk($array_collections, 'replace_null');

PHP Checking if Array is empty logic not working

I have a page that loads and creates an empty array:
$_SESSION['selectedItemIDs'] = array();
If the user hasn't added any selections that get stored in the array I then check the array and branch accordingly, but there appears to be some error in my logic/syntax that is failing here.
Here's where I test if the $_SESSION['selectedItemIDs'] is set but empty:
if (isset($_SESSION['selectedItemIDs']) && $_SESSION['selectedItemIDs'] !== '') {
// update the selections in a database
} else {
// nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}
When testing this with no selections if I print the $_SESSION['selectedItemIDs'] array I get this:
[selectedItemIDs] => Array
(
)
however the $selectedItems variable is not being set - it's evaluating the if test as true when I would expect it to be false, but I'm obviously misunderstanding something here.
Use empty() function.
empty() - it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
Syntax
empty(var_name)
Return value
FALSE if var_name has a non-empty and non-zero value.
Value Type :
Boolean
List of empty things :
"0" (0 as a string)
0 (0 as an integer)
"" (an empty string)
NULL
FALSE
"" (an empty string)
array() (an empty array)
$var_name; (a variable declared but without a value in a class)
Code
if (!empty($_SESSION['selectedItemIDs']) ) {
// update the selections in a database
} else {
// nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}
$_SESSION['selectedItemIDs'] = array();
this variable is already set, but is empty.
isset($_SESSION['selectedItemIDs']) check if variable exists, even if it's nothing in.
To check if there is anything just use
empty($_SESSION['selectedItemIDs']);
PHP DOC - empty
if (!empty($_SESSION['selectedItemIDs'])) {
// update the selections in a database
} else {
// nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}
isset($_SESSION['selectedItemIDs']) => it will check is this parameter is set or not which is correct.
$_SESSION['selectedItemIDs'] !== '' => this will exactly compare that your parameter type is not '' but here i guess your selectedItemIDs is array so it let you go inside
You can check the count of this array.
if (isset($_SESSION['selectedItemIDs']) && count($_SESSION['selectedItemIDs']) > 0) {
// update the selections in a database
} else {
// nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}

PHP verify array elements are all empty

I need to ensure that all the elements in my array are empty strings to process an action. The way I am currently doing it is incrementing a variable each time an element is an empty string. Then I check the value of that variable against a certain requirement N. If N is met, the action is processed. Below is the snippet of the code that checks for empty strings. I am not sure if this is the best way to do it and think there has to be a better way to do it because basically I am hard coding that value N. Can anybody else suggest another approach?
function checkErrorArray($ers) {
$err_count = 0;
foreach ($ers as &$value) {
if ($value == '') {
$err_count++;
}
}
return $err_count;
}
Why don't you do:
function areAllEmpty($ers) {
foreach ($ers as &$value) {
//if a value is not empty, we return false and no need to continue iterating thru the array
if (!empty($value)) return false;
}
//if got so far, then all must be empty
return true;
}
It will not have to run through the whole array if a non-empty value is found.
You could also do a shorter version:
function areAllEmpty($ers) {
$errs_str = implode('', $ers);//join all items into 1 string
return empty($errs_str);
}
Hope this helps.
Just filter it and if it is empty then ! will return true if not empty it will return false:
return !array_filter($ers);
Or if you actually need the count of empty elements then:
return count(array_diff($ers, array_filter($ers)));

Workaround for isset, array_key_exists and !empty [duplicate]

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).

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