How to Remove Empty Array Elements and reindex in PHP Example?

How to Remove Empty Array Elements and reindex in PHP Example?

In this post we will give you information about How to Remove Empty Array Elements and reindex in PHP Example?. Hear we will give you detail about How to Remove Empty Array Elements and reindex in PHP Example?And how to use it also give you demo for it if it is necessary.

In this post, I will tell you how to remove empty values from array in PHP by using array_filter function.

array_filter function remove all elements from given array that are equal to boolean false and emtpy string always return boolean false.

So question is it that 0 is also return boolean false then array_filter will remove 0 too then how will you keep it in array ?


Example 1: array_filter() function

  1. $my_array=array(,"onlinecode","","Demo");
  2. $resultDirect=array_filter($my_array);
  3. print_r($resultDirect);
$my_array = array(0, "onlinecode", "","Demo");
$resultDirect = array_filter($my_array);
print_r($resultDirect);

Output :

  1. Array
  2. (
  3. [1]=> onlinecode
  4. [3]=> Demo
  5. )
Array
(
    [1] => onlinecode
    [3] => Demo
)


Example 2: array_diff() function

  1. $my_array=array(,"onlinecode","","Demo");
  2. echo"
    "

    ;

  3. print_r(array_diff($my_array,array('')));
$my_array = array(0, "onlinecode", "","Demo");
echo "
";
print_r( array_diff( $my_array, array( '' ) ) );

Output:

  1. Array
  2. (
  3. []=>
  4. [1]=> onlinecode
  5. [3]=> Demo
  6. )
Array
(
    [0] => 0
    [1] => onlinecode
    [3] => Demo
)

array_diff() function return all the element of first array except element that present in second array.

You can remove empty value and then reindex array elements too.

  1. $my_array=array(,"onlinecode","","Demo");
  2. $resultDirect=array_values(array_filter($my_array));
  3. echo"<pre>";
  4. print_r($resultDirect);
$my_array = array(0, "onlinecode", "","Demo");
$resultDirect = array_values(array_filter($my_array));
echo "<pre>";
print_r($resultDirect);

Output:

  1. Array
  2. (
  3. []=> onlinecode
  4. [1]=> Demo
  5. )
Array
(
    [0] => onlinecode
    [1] => Demo
)

Hope this code and post will helped you for implement How to Remove Empty Array Elements and reindex in PHP Example?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  37  =  45

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US