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

2

7 Answers 7

3

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

<?php if(empty($myArray)) { //condition } ?> 
Sign up to request clarification or add additional context in comments.

Comments

1
if (! count($myArray)) { // array is empty } 

Let php do its thing and check for booleans.

Comments

1

Use empty:

if (empty($myArray)) { ... } 

Comments

1

Try this :

<?php $array = array(); if(empty($array)) { echo "empty"; } else { echo "some thing!"; } ?> 

Comments

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

Comments

0
 <?php if(empty($yourarry)){ } 

OR

if(isset($yourarry)){ } 

OR

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.