-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
  • 127
  • 1
  • 5

7 Answers7

3

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

<?php   
    if(empty($myArray)) {
      //condition
    }
 ?>
mario.van.zadel
  • 2,919
  • 14
  • 23
Vivek Singh
  • 2,453
  • 1
  • 14
  • 27
1
if (! count($myArray)) {
    // array is empty
}

Let php do its thing and check for booleans.

Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44
1

Use empty:

if (empty($myArray)) {
   ...
}
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

Try this :

<?php

$array = array();
if(empty($array))
{
 echo "empty";
} else
{
echo "some thing!";
}
?>
Vipin Sharma
  • 421
  • 5
  • 24
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,898
  • 1
  • 23
  • 38
0
    <?php 

if(empty($yourarry)){

}

OR

if(isset($yourarry)){


}

OR

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

}
santosh
  • 799
  • 5
  • 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,989
  • 6
  • 28
  • 46