PHP if array is empty - php

I have an array and when I print the output like so print_r($userExists);
it returns Array ( ) I wrote this code to tell me if the array is empty or not:
if(isset($userExists)){
echo 'exists';
}else{
echo 'does not exists';
}
But regardless if the array is empty or not, it only returns exists What Am i doing wrong, when the array is populated, it looks like this Array ( [0] => Array ( [id] => 10 ) )

Use
if( !empty( $userExists ) ) {
echo 'exists';
}
else {
echo 'does not exists';
}
or
if( count( $userExists ) ) {
echo 'exists';
}
else {
echo 'does not exists';
}
However is safer to use empty() as if that variable doesn't exists your script will not stop due to exception while count() does.
isset is "not working"* here since this variable is setted (so exists) even if is empty.
So, basically, isset will
Determine if a variable is set and is not NULL.
Last but not least, if you want to know which is "better" for code optimization, I could tell you a little "secret": count() doesn't need to traverse the array each time to know how many elements will be there since, internally, it store the elements number (as you can see under), so every call to count() function results in O(1) complexity.
ZEND_API int zend_hash_num_elements(const HashTable *ht)
{
IS_CONSISTENT(ht);
return ht->nNumOfElements;
}
zend_hash_num_elements is called from count() (take a look here)
from php manual
*(not working as you wish/need)

use as below
if(isset($userExists) && count($userExists) > 0 ){
echo 'exists';
}else{
echo 'does not exists';
}
OR
You can check if the variable is an array and having some value
if(is_array($userExists) && count($userExists) > 0 ){
echo 'exists';
}else{
echo 'does not exists';
}

$userExists = array();
The variable exists, and it is set. That's what isset tests for.
What you want is:
if( $userExists) echo "exists";

You do not need an extra check for if!
if($array){
// Will execute only if there is any value inside of the array
}
By using if there is no need checking if any value is available!
you are using 'isset' for variables that might not exist like $_GET value or $_SESSION etc....
'empty' to check a string value
by php documentation empty works only in string and not arrays

Related

Is this the correct way of checking empty array?

I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.

Check if 2 vars are not in array in php

This is one is confusing me.
I am trying to check if 2 vars are not in an array with an OR, but it returns the opposite results than the expected.
Does 2 !in_array, in conjunction with an OR, creates 2 negatives = positive?
The case:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) || !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Since 2 is in the array, I expect the script to echo "In Array", but it echoes "Not in Array". If I remove the second !in_array after the OR, it echoes "In Array". If I change the OR with an AND, it echoes "In Array".
It doesn't make much sense, or I am just that confused at the moment. Can someone give some input?
The problem is you are using || instead of &&. What the logical OR (||) does is that it checks the first condition and if it is true then it does not test the other conditions in the if statement. Here is the revised code:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Hope this helps!
Try this:
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
This will ensure that when both (&&) 0 and 2 are not in the array, it prints "Not in array"
As stated in my comment, you should be checking that the first value and the second value are not in the array: !in_array(2, $user->groups) && !in_array(0, $user->groups).
For two conditions, I would consider the following suggestion overkill but you may find it useful if you want to search for a larger number of values:
$arr = array(1,2,3);
$search = array(1,2);
$all_in = function($prev, $curr) use ($arr) {
return $prev && in_array($curr, $arr);
};
if (array_reduce($search, $all_in, true)) {
echo 'all values in $search are in $arr';
}
else {
echo 'some of the values in $search are not in $arr';
}
array_reduce applies the callback function $all_in to each of the values of the $search array and keeps track of a boolean value (initialised to true) that remains true as long as all the values are in the array $arr.
As I said, this approach isn't particularly useful if you're only looking for two values but one benefit is that you can easily add values to the $search array without changing any of the other code.

isset() or array_key_exists() doesnt work with $_POST

I have a VERY simple code, I dont know what I am doing wrong. I am sending post variables with Ajax, there are 3 checkboxes (an array) name="options[]".. I am receiving the right array, if I check Option1, Option2 or Option3, I get the correct Array.. but when I try to check and confirm them with isset() or with array_key_exist() it does not give me the right answers.. For example, if I only check Option 1 and 3, I get the following in the POST
[options] => Array
(
[0] => option_one
[1] => option_two
)
I need to do some action only IF the certain key does NOT exist in the array.. I tried something like below..
if (array_key_exists("option_one", $_POST['options'])) {
echo "Option one exists";
} else {
echo "option one does not exist";
}
it returns flase results, then I tried using ! (not) before it, that returns the same result. Then I tried with isset($_POST['options']['option_one']) without any luck.. then I tried the following function to check again within the array..
function is_set( $varname, $parent=null ) {
if ( !is_array( $parent ) && !is_object($parent) ) {
$parent = $GLOBALS;
}
return array_key_exists( $varname, $parent );
}
and used it like this
if (is_set("option_one", $_POST['options'])) {
echo "Option one exists";
} else {
echo "option one does not exist";
}
nothing works, it simply returns false value. I tried with $_REQUEST instead if $_POST but no luck, I have read many threads that isset() or array_key_exists() returns false values.. What is the solution for this ? any help would be highly appreciated.. I am tired of it now..
regards
option_one is not a key in the array, it's a value. The key is 0. If anything, use:
in_array('option_one', $_POST['options'])
array_key_exists looks for the keys of the arrays. You are looking for the value. :)
What you want is
/**
* Check wheter parameter exists in $_POST['options'] and is not empty
*
* #param $needle
* #return boolean
*/
function in_options($needle)
{
if (empty($_POST['options']))
return false;
return in_array($needle, $_POST['options']);
}
Are you sure you are getting the correct information in your options[] array? If you clicked option 1 and option 3, shouldn't the array look something like this?
[options] => Array
(
[0] => option_one
[1] => option_three
)
Since isset() is a language construct and not a function, you may be able to rework the validation to be more efficient.
function in_options($needle)
{
//Checking that it is set and not NULL is enough here.
if (! isset($_POST['options'][0]))
return false;
return in_array($needle, $_POST['options']);
}
The function empty() works, but I think that $_POST['options'][0] only needs to be checked for isset() at this point.

if array undefined

How do I check if an array is undefined?
I am using isset and empty but both of them are not working for an undefined array.
This is my code:
if (isset($content['menu']['main'])){
echo 'there is menu';
}
use this code as specified by Rikesh and mimipc
$arr = array("menu"=>array("main"=>1));
if (is_array($arr) && array_key_exists('menu', $arr)) {
echo "array";
}
working example http://codepad.viper-7.com/Q3gTwn
Based on your code, I think you're looking for the function array_key_exists().
$content = array('menu'=>array());
echo isset($content);
>>> 1
echo array_key_exists('menu', $content);
>>> 1
if ( array_key_exists('main', $content['menu']) ) {
echo "Main menu exists";
} else {
echo "Main menu does not exist";
}
>>> Main menu does not exist
isset() will not work, because the variable $content is set, and the array may not be empty, so empty() will also not work. You want to see if the main key exists in the $content['menu'] array.
You can check if an array element exists with in_array:
in_array('one', array('two', 'three', 'four')); // false
And you can check array-indexes with array_key_exists:
array_key_exists('metallica', array('metallica' => 'worst than megadeth')); // true
With the isset function you only check if the array or variable is not equal to NULL and if it contains a value which can be interpreted as boolean True or False, integers larger than 0 and if the variable value (or array key/index/element) is not equal to NULL.
I usualy check if variable is set with: is_null, and it can be used to check if an array index or an element is defined within that same array.
EDIT:
You can also check if a variable is array with: (sizeof($something) > 0) or with: is_array function(s).

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

Categories