PHP Checking if Array is empty logic not working - php

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';
}

Related

How to detect when "0" is supplied as a form/$_POST value?

I'm trying to determine whether or not there is a value passed, but the value CAN be 0 ...
isset always returns true, and empty returns false because the value is 0
How can I get around this?
try
bool array_key_exists ( mixed $key , array $array )
like
if (array_key_exists("var1", $_POST)) {
// positive case, var1 was posted
if ($_POST["var1"] == 0){
// var1 was posted and 0
}else{
// var1 was posted and is not 0
}
}
more details are given at the docs.
The values of the $_POST array is all strings. Use the === operator:
if ($_POST['key'] === '0') {
// do things
}
Try this
if (isset($_POST['name']) && $_POST['name'] != 0)) {
/your Code/
}
What about simply checking whether the value is empty:
if (isset($_POST['key']) && $_POST['key'] !== '')) {
//'key' is set and not empty
}
All post values are strings, so consider:
isset($a[i]) && strlen($a[i])
Which will be true if and only if a value (except "an empty string") is supplied. Unlike with empty, which would return FALSE, this will also detect when "0" was passed as a value. Unlike the proposed solution, it will not be true when "" was supplied: thus it truly detects when a value was passed.
Also, array_key_exists and isset for $_POST keys will work the same, as there will no NULL values; arguably the critical check is that for a non-empty string. Once a value has been determined to exist (per the above/desired rules), it can be processed as appropriate - e.g. if ($a[i] > 0) or if ($a[i] == 0).

php if and isset and if variable is not set and doesnt exist

Possibly a strange one that I hope can be done in one line.
I have to have an IF statement that will checks two things.
The first checks if the variable $loggedInfo['status'] is set and is equal to "client".
The second checks that the variable $loggedInfo['address1'] is set and is blank.
The reason being that when the first variable equals staff then the 'address1' variable doesn't exist.
I did have the following but when I log in as staff it still checks for the address1
if((isset($loggedInfo['status'])=="client")&&(!$loggedInfo['address1'])){
//Do something
}
isset returs true or false. you have to do separate check for the actual value
if(
isset($loggedInfo['status']) && $loggedInfo['status']=="client" &&
isset($loggedInfo['address1']) && trim($loggedInfo['address1']) != ''
)
{
//Do something
}
if((isset($loggedInfo['status']) && $loggedInfo['status']=="client") &&(empty($loggedInfo['address1'])){
//Do something
}
isset() returns TRUE if the given variable is defined in the current scope with a non-null value.
empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:
NULL // NULL value
0 // Integer/float zero
'' // Empty string
'0' // String '0'
FALSE // Boolean FALSE
array() // empty array
Depending PHP version, an object with no properties may also be considered empty.
Well you just can't compare the return value of isset() with the string "client", because it will never equal that. To quote http://php.net/manual/en/function.isset.php its return values are "TRUE if var exists and has value other than NULL, FALSE otherwise".
First check if it is set
if ((isset($loggedInfo['status']) === true) && ($loggedInfo['status'] === "client") && (empty($loggedInfo['address1']) === true)) {
// Do something
}
Key take away from this should be to look up return values for every function you use, like empty(), in the manual http://www.php.net/manual/en/function.empty.php. This will save you a lot of headaches in the future.

PHP: checking key value is not empty

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

Check whether an array is empty [duplicate]

This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I have the following code
<?php
$error = array();
$error['something'] = false;
$error['somethingelse'] = false;
if (!empty($error))
{
echo 'Error';
}
else
{
echo 'No errors';
}
?>
However, empty($error) still returns true, even though nothing is set.
What's not right?
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.
Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
Try to check it's size with sizeof if 0 no elements.
PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.
If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.
$set_errors = array_keys( $errors, true );
You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.
array with zero elements converts to false
http://php.net/manual/en/language.types.boolean.php
However, empty($error) still returns true, even though nothing is set.
That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.
From the PHP-documentation:
Returns FALSE if var has a non-empty and non-zero value.
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 $var; (a variable declared, but without a value in a class)
function empty() does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye
(sorry for my english)
hi array is one object so it null type or blank
<?php
if($error!=null)
echo "array is blank or null or not array";
//OR
if(!empty($error))
echo "array is blank or null or not array";
//OR
if(is_array($error))
echo "array is blank or null or not array";
?>
I can't replicate that (php 5.3.6):
php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)
php > $error = array();
php > var_dump(empty($error));
bool(true)
php >
exactly where are you doing the empty() call that returns true?
<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject) function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true

php: check if certain item in an array is empty

In PHP, how would one check to see if a specified item (by name, I think - number would probably also work) in an array is empty?
Types of empty (from PHP Manual). The following are considered empty for any variable:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
So take the example below:
$arr = array(
'ele1' => 'test',
'ele2' => false
);
1) $arr['ele3'] is not set. So:
isset($arr['ele3']) === false && empty($arr['ele3']) === true
it is not set and empty. empty() checks for whether the variable is set and empty or not.
2) $arr['ele2'] is set, but empty. So:
isset($arr['ele2']) === true && empty($arr['ele2']) === true
1) $arr['ele1'] is set and not empty:
isset($arr['ele1']) === true && empty($arr['ele1']) === false
if you wish to check whether is it empty, simply use the empty() function.
if(empty($array['item']))
or
if(!isset($array['item']))
or
if(!array_key_exists('item', $array))
depending on what precisely you mean by "empty". See the docs for empty(), isset() and array_key_exists() as to what exactly they mean.
<?php
$myarray=array(1,5,6,5);
$anotherarray=array();
function checkEmpty($array){
return (count($array)>0)?1:0;
}
echo checkEmpty($myarray);
echo checkEmpty($anotherarray);
?>
(for checking if empty result 1 else 0);
Compactness is what I persue in my code.
i had such situation where i was getting tab it last index of array so if put things together then this might work for the most of cases
<?php
if( ctype_space($array['index']) && empty($array['index']) && !isset($array['index']) ){
echo 'array index is empty';
}else{
echo 'Not empty';
}

Categories