-2

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.

yo black
  • 97
  • 1
  • 4

7 Answers7

3

you can check it by using empty() function like below

<?php   
    if(empty($myArray)) {
      //condition
    }
 ?>
mario.van.zadel
  • 2,878
  • 13
  • 20
Vivek Singh
  • 2,445
  • 1
  • 13
  • 26
1
if (! count($myArray)) {
    // array is empty
}

Let php do its thing and check for booleans.

Swaraj Giri
  • 3,889
  • 2
  • 22
  • 40
1

Use empty:

if (empty($myArray)) {
   ...
}
Zbynek Vyskovsky - kvr000
  • 17,458
  • 2
  • 33
  • 41
1

Try this :

<?php

$array = array();
if(empty($array))
{
 echo "empty";
} else
{
echo "some thing!";
}
?>
Vipin Sharma
  • 421
  • 5
  • 23
0

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) ){
    .....
    .....
}
Haridarshan
  • 1,852
  • 1
  • 23
  • 37
0
    <?php 

if(empty($yourarry)){

}

OR

if(isset($yourarry)){


}

OR

if(count($yourarry)==0){

}
santosh
  • 791
  • 4
  • 17
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.

Sjon
  • 4,833
  • 6
  • 26
  • 45