PHP Empty Array

PHP Empty Arrays
How to find PHP Empty Arrays

PHP Empty Array

In our earlier post we have explained what a PHP array is. It you want to learn more about PHP arrays see our post PHP Arrays | Indexed, Associative and Multidimensional PHP Arrays. So the PHP empty array is an array that has no element in it or a empty PHP array is that has a count or length of 0 (zero). Now we are going to tell you that how many ways there are to create empty PHP array.

PHP Empty Arrays

How to find PHP Empty Arrays

PHP Create Empty Array

There are three ways to create an empty PHP array.

 
     $my_array = array(); //It can be used prior to PHP 5.4
     $my_array = []; //It can be used with PHP 5.4 and higher
     $my_array = (array) null;
    

If you have a PHP array with values and want to delete all the elements of the array you can use a PHP array function to make an empty PHP array. Here is PHP create empty array code to empty a PHP array:

unset($my_array);

Note: The unset() PHP array function can be used to delete a single element as well.

How to check an empty PHP array?

There are 3 ways we are going to use to find out if an array is empty or not.

  • Using empty() function
  • Using count() function
  • Using sizeof() function

1 – Find out PHP empty array using empty() PHP function

Syntax of empty() function bool empty($variable);
<?php
    $my_empty_array = array();
	$my_array = array('Howtocde.pk', 'PHP tutorials');
	
	if(empty($my_empty_array)){
		echo 'The $my_empty_array array is empty.
';
	}else{
		echo 'The $my_empty_array array is not empty.
';
	}
	
	if(empty($my_array)){
		echo 'The $my_array array is empty.
';
	}else{
		echo 'The $my_array array is not empty.
';
	}
?>

Output:

The $my_empty_array array is empty.
The $my_array array is not empty.

2 – Find out PHP empty array using PHP count() function

Syntax of count() function int count($array);
<?php $my_array2 = array('URL' => 'https://www.howtocode.pk'); 
    $my_empty_array2 = array(); 
	
    if(count($my_empty_array2) > 0){
		echo 'The $my_empty_array2 array is not empty.';
	}else{
		echo 'The $my_empty_array2 array is empty.';
	}
	
	if(count($my_array2) > 0){
		echo 'The $my_array2 array is not empty.';
	}else{
		echo 'The $my_array2 array is empty.';
	}
?>

Output:

The $my_empty_array2 array is empty.
The $my_array2 array is not empty.

3 – Find out PHP empty array using PHP sizeof() function

Syntax of sizeof() function int sizeof($array);
<?php $my_array3 = array('mobile' => 'https://www.howtocode.pk/what-mobile/'); 
    $my_empty_array3 = array(); 
	
 
	if(sizeof($my_empty_array3) == 0){
		echo 'The $my_empty_array3 array is empty.';
	}else{
		echo 'The $my_empty_array3 array is not empty.';
	}
	
	if(sizeof($my_array3) == 0){
		echo 'The $my_array3 array is empty.';
	}else{
		echo 'The $my_array3 array is not empty.';
	}
?>

Output:

The $my_empty_array3 array is empty.
The $my_array3 array is not empty.

 

Comments