15

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?

4 Answers 4

52

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oooh, helpful. I would upvote you guys if I had enough rep. Heh.
16
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.

3 Comments

OK. What kinds of empty are there?
Addendum: I think the item(s) I'm dealing with look like => '', What would that be?
That will be empty, set, and existant.
0
<?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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.