if array undefined - php

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

Related

isset() or empty() statements not giving desired results

I am using the following code which is giving the same result irrespective of the condition;
foreach($data as $row)
{
$a = $row['name']; //Here I am calling name from an api
if(empty($a))
{
$a = 'AAA'; // Checking if a$ = $row['']; i.e. 'name' does not exist
}
echo $a;
}
The problem is when $row['name'] has value, it is getting echoed via $a, but if $row['name'] does not exist, I am getting error as undefined index: (probably for since 'name' is not available for that row.)
How to get $a echoed as 'AAA' in case $row['name'] does not exist?
Try checking the actual array and not the declaration of the null.
if(!isset($row['name']))
$a = "AAAA";
https://ideone.com/RuqOBs
The difference is subtle but important :
isset — Determine if a variable is set and is not NULL
empty — Determine whether a variable is empty
is_null — Finds whether a variable is NULL
write the else part like this :
foreach($data as $row){
if(empty($row['name']) || ! isset($row['name']) )
{
$a = 'AAA';}
}
else
{
$a = $row['name'];
}
echo $a;
}
isset() checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if var exists; FALSE otherwise.
On the other hand the empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.
Check to see if name is set before doing your test and combine then into a single statement.
$a = (isset($row['name']) ? $row['name'] : 'AAA');
echo $a;
There are three functions to choose from, which have the following differences:
array_key_exists($key, $array)
This will check if the key exists in the array. If it does, no matter what value is stored behind it (even null), it will return true, false oterhwise.
isset($array[$key])
This will check if the key in the array exists and if the value behind it is not null. If it exists and is not null it will return true, false oterhwise.
empty($array[$key])
This will check if the key exists and if the value behind it is falsy. If it does not exist or the value is falsy (For example null, false, '' or 0) it will return true, false otherwise.
All those functions have in common, that you call them on the array directly. For you, you could call it like this:
foreach($data as $row) {
echo array_key_exists('name', $row) ? $row['name'] : 'AAA';
}
You can exchange array_key_exists('name', $row) with any of the other two functions, depending of what kind of behavior you want.

How to check if an array value exists in PHP [duplicate]

Example: I'm checking for the existence of an array element like this:
if (!self::$instances[$instanceKey]) {
$instances[$instanceKey] = $theInstance;
}
However, I keep getting this error:
Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16
Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?
You can use either the language construct isset, or the function array_key_exists.
isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset :
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
boolean true
While the second one will get you (the element exists, but is null) :
boolean false
And the last one will get you (the element doesn't exist) :
boolean false
On the other hand, using array_key_exists like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'd get those outputs :
boolean true
boolean true
boolean false
Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.
For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}
array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.
It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)
if (isset($a['element']) || array_key_exists('element', $a)) {
//the element exists in the array. write your code here.
}
The benchmarking comparison: (extracted from below blog posts).
array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms
See
http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/
and
http://thinkofdev.com/php-isset-and-multi-dimentional-array/
for detailed discussion.
You can use the function array_key_exists to do that.
For example,
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
PS : Example taken from here.
You can use isset() for this very thing.
$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
According to the PHP manual you can do this in two ways. It depends what you need to check.
If you want to check if the given key or index exists in the array use array_key_exists
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
If you want to check if a value exists in an array use in_array
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>
You want to use the array_key_exists function.
A little anecdote to illustrate the use of array_key_exists.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
You can also use array_keys for number of occurrences
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>

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

In where shall I use isset() and !empty()

I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.
So you can use empty() to check that a user typed something.
Is it true that the isset() function treats an empty string as TRUE?
Then in which situations should I use isset()? Should I always use !empty() to check if there is something?
For example instead of
if(isset($_GET['gender']))...
Using this
if(!empty($_GET['gender']))...
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.
On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
In the most general way :
isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
empty tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty.
Neither is a good way to check for valid input.
isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
! empty() is not sufficient either because it rejects '0', which could be a valid value.
Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:
if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).
For that, see Josh Davis's answer.
isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.
So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:
$var = "";
var_dump(isset($var));
The type comparison tables in PHP’s manual is quite handy for such questions.
isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
isset() is not an effective way to validate text inputs and text boxes from a HTML form
You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.
Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.
When and how to use:
isset()
True for 0, 1, empty string, a string containing a value, true, false
False for null
e.g
$status = 0
if (isset($status)) // True
$status = null
if (isset($status)) // False
Empty
False for 1, a string containing a value, true
True for null, empty string, 0, false
e.g
$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
isset() vs empty() vs is_null()
isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...
Pascal MARTIN... +1
...
empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
isset($variable) === (#$variable !== null)
empty($variable) === (#$variable == false)
I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is '' or null, because:
Request URL .../test.php?var= results in $_GET['var'] = ''
Request URL .../test.php results in $_GET['var'] = null
isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').
empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.
If you want to treat '0' as empty, then use empty(). Otherwise use the following check:
$var .'' !== '' evaluates to false only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}
Using empty is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the # prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && #$_GET['var']!='' ){
//Is not empty, do something
}
$var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
echo '$var is set even though it is empty';
}
Source: Php.net
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Please consider behavior may change on different PHP versions
From documentation
isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php
empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php
(empty($x) == (!isset($x) || !$x)) // returns true;
(!empty($x) == (isset($x) && $x)) // returns true;
When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.
if(empty($yourVal)) {
echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
echo "<P>YES isset - $yourVal"; // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}

How can I check if an array element exists?

Example: I'm checking for the existence of an array element like this:
if (!self::$instances[$instanceKey]) {
$instances[$instanceKey] = $theInstance;
}
However, I keep getting this error:
Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16
Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?
You can use either the language construct isset, or the function array_key_exists.
isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset :
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
boolean true
While the second one will get you (the element exists, but is null) :
boolean false
And the last one will get you (the element doesn't exist) :
boolean false
On the other hand, using array_key_exists like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'd get those outputs :
boolean true
boolean true
boolean false
Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.
For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}
array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.
It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)
if (isset($a['element']) || array_key_exists('element', $a)) {
//the element exists in the array. write your code here.
}
The benchmarking comparison: (extracted from below blog posts).
array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms
See
http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/
and
http://thinkofdev.com/php-isset-and-multi-dimentional-array/
for detailed discussion.
You can use the function array_key_exists to do that.
For example,
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
PS : Example taken from here.
You can use isset() for this very thing.
$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
According to the PHP manual you can do this in two ways. It depends what you need to check.
If you want to check if the given key or index exists in the array use array_key_exists
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
If you want to check if a value exists in an array use in_array
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>
You want to use the array_key_exists function.
A little anecdote to illustrate the use of array_key_exists.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
You can also use array_keys for number of occurrences
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>

Categories