1021

Some elements in my array are empty strings from users. $linksArray still has empty elements after the following:

foreach($linksArray as $link)
{
    if($link == '')
    {
        unset($link);
    }
}
print_r($linksArray);

The empty() function doesn't work either.

Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
Will
  • 10,731
  • 6
  • 22
  • 16
  • 4
    I thought it was worth mentioning that the code above does not work because unset(...) operates on the variable created by the foreach loop, not the original array that obviously stays as it was before the loop. – savedario Feb 17 '17 at 09:42
  • 1
    if(!empty($link)) { echo $link; } this works for me – Shiplu Jul 21 '19 at 08:23
  • 2
    U are changing a $link that is not refferenced! use foreach($linksArray as $key => $link) unset(linksArray[$key]) – Nijboer IT Mar 22 '20 at 11:37
  • https://stackoverflow.com/a/66004034/7186739 – Billu Oct 10 '21 at 09:48

27 Answers27

1975

As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

$linksArray = array_filter($linksArray);

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback:

// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));

// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));

// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));

Note: If you need to reindex the array after removing the empty elements, use:

$linksArray = array_values(array_filter($linksArray));
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • That was a typo haha, sorry. It's correct in my real code. Thanks for the answer :) – Will Sep 06 '10 at 21:15
  • 2
    I would use `empty` over `== ''`. But thanks for the reference :) – Jim Jun 01 '12 at 20:26
  • 17
    `array_filter` should remove the empty elements. And if PHP's definition of empty isn't quite the same as your definition, then you can fill in the callback option with an anonymous function that throws out unwanted elements. Apparently you must have php 5.3 or later to use anonymous call backs. http://stackoverflow.com/questions/2412299/how-do-you-use-anonymous-functions-in-php – Buttle Butkus May 19 '13 at 22:55
  • it always pays to fully read the documentation. I didn't know it auto-filtered out empty elements. Thanks @BoltClock. – Matthew Setter Jul 05 '13 at 08:19
  • use array_filter($linksArray,'trim'); – Ankit Sharma Apr 25 '14 at 13:59
  • 85
    watch out array_filter doesnt reindex array indexes (a problem may occur in using processes array in for statement). So wrap it all with array_values function. – Michal - wereda-net May 29 '14 at 07:36
  • 1
    Use this function for a multidimensional array: `$linksArray = array_filter(array_map('array_filter', $linksArray));` – joseantgv Dec 31 '14 at 13:36
  • not better foreach (array_keys($locations,"") as $k) unset($locations[$k]); – fearis Jun 01 '15 at 12:24
  • Take `$a = array('a'=>5, 'b'=>6, 'a'=>5);`, then `array_filter($a));`, the result is `array('a'=>5, 'b'=>6)` - `array_filter()` removes duplicates too, so not so good for just removing nulls. – Deji Aug 17 '15 at 13:25
  • 10
    Answer is incorrect, because it will remove `false` elements too. (http://php.net/manual/en/function.array-filter.php) – pliashkou Oct 21 '15 at 06:39
  • 5
    @Deji have you tried printing that array before filtering it? I think setting `a` the second time just resets the first one. – Cullub Jan 31 '16 at 00:10
  • 7
    @Cranio: which is already covered by another comment. It is not incorrect, but perhaps *broader* than **your** requirements. That doesn't mean other people can't find it helpful still; after all, if all you have is strings in your array, this answer will remove only the empty ones. – Martijn Pieters Jul 18 '16 at 10:04
  • 1
    I wish someone had told me that 4 years ago. – Adam Nov 13 '17 at 17:28
  • Would you mind updating the answer with PHP 7.4 version (arrow functions) and adding a warning about deprecated `create_function()`? – Dharman Mar 01 '20 at 14:06
  • @Dharman: Done. I don't think I need to say that create_function() is deprecated since there's already a note saying to use it for older versions of PHP, but I moved it to the bottom. – BoltClock Mar 10 '20 at 03:20
  • This was really helpfull because was getting empty strings on a dynamic form, thank you really much. used atm 5.3 later, as im not using atm php 7.4 only 7.1. – Rodrigo Zuluaga Mar 31 '20 at 14:43
  • watch out: array_filter takes an array and returns an object. So how to get an array returned instead of an object? – Imran_Developer Nov 18 '21 at 09:48
  • @Imran_Developer: When did that happen? I just checked the manual and it doesn't mention this behavior having changed. array_filter() returns an array. – BoltClock Nov 18 '21 at 09:50
  • @BoltClock dear, I am working with APIs and got a different JSON response so I was surprised, it really changes the behavior. i have double-checked with postman – Imran_Developer Nov 18 '21 at 11:21
200

You can use array_filter to remove empty elements:

$emptyRemoved = array_filter($linksArray);

If you have (int) 0 in your array, you may use the following:

$emptyRemoved = remove_empty($linksArray);

function remove_empty($array) {
  return array_filter($array, '_remove_empty_internal');
}

function _remove_empty_internal($value) {
  return !empty($value) || $value === 0;
}

EDIT: Maybe your elements are not empty per se but contain one or more spaces... You can use the following before using array_filter

$trimmedArray = array_map('trim', $linksArray);
rybo111
  • 12,240
  • 4
  • 61
  • 70
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • 11
    I just added it to the accepted answer by BoltClock, you could simply do array_filter($foo, 'strlen') to avoid the "0" issue and only remove those with zero length. – A.B. Carroll Apr 26 '13 at 18:27
  • 2
    @nezZario: Assuming you only have `scalar` items in your array yes. Otherwise, you cannot do that. – Andrew Moore Jun 24 '13 at 21:39
  • 2
    Using lambda for php >= 5.3 `function remove_empty($array) { return array_filter($array, function($value){return !empty($value) || $value === 0;}); }` – viral Aug 27 '15 at 18:33
  • 2
    `array_map()` did the magic cos I had spaces in those empty arrays! – Prodigy Feb 12 '17 at 13:39
185

The most popular answer on this topic is absolutely INCORRECT.

Consider the following PHP script:

<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));

Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug.

Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.

So, the absolute, definitive, correct answer is:

$arr = array_filter($arr, 'strlen');
Philipp
  • 2,787
  • 2
  • 25
  • 27
Ron Cemer
  • 1,876
  • 1
  • 11
  • 3
  • 6
    Agreed. This should be the accepted answer, for those whose array contains strings – mwieczorek Sep 07 '16 at 11:06
  • 2
    Upvoted. A better answer than many of the others, however it should be noted that the currently-accepted answer is technically not incorrect since "empty" does, indeed, have special meaning within PHP. (Some values that qualify as "empty": `0`, `""`, `null`) – rinogo May 04 '17 at 01:45
  • 7
    They are not incorrect, it's all about context. In some cases preserving the value 0 could be important. So please, don't say that everyone is wrong except you – Macr1408 Sep 26 '18 at 20:57
  • 12
    This breaks if the array contains another array: `strlen() expects parameter 1 to be string, array given` – hpaknia Oct 28 '18 at 07:11
  • 1
    You can say that this can also be a good approach (instead of saying others incorrect)to achieve one's desired actions.Basically not all the cases are similar .Although this approach is working for my case. – MR_AMDEV May 01 '19 at 23:15
  • And if you want to filter out null values and other none scalar types you can use `'is_scalar'`. Do note that in this case, an empty string would be allowed. – Pablo Mar 17 '20 at 15:43
  • Take care if you are dealing with nested arrays as @hpaknia said. This solution only works with arrays of strings. – Xus Jan 25 '21 at 10:56
  • From PHP8.1 `strlen` is no longer a good technique because it will generate Deprecations. `Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated` – mickmackusa May 26 '22 at 06:25
110
$linksArray = array_filter($linksArray);

"If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php

tamasd
  • 5,747
  • 3
  • 25
  • 31
  • 4
    I also tried this after Google'ing the problem. Unfortunately, it leaves in the blank elements for me. – Will Sep 06 '10 at 21:16
  • 2
    @Will: are you sure? It removes also empty strings, I successfully tested this. Maybe your input values contain spaces and should be trimmed before. According to the [boolean conversion rules](http://de3.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting) the empty string is evaluated to false and therefore removed by array_filter. – acme Mar 12 '12 at 11:26
58
    $myarray = array_filter($myarray, 'strlen');  //removes null values but leaves "0"
    $myarray = array_filter($myarray);            //removes all null values
matija kancijan
  • 1,205
  • 10
  • 11
45

You can just do

array_filter($array)

array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.

The other option is doing

array_diff($array, array(''))

which will remove elements with values NULL, '' and FALSE.

Hope this helps :)

UPDATE

Here is an example.

$a = array(0, '0', NULL, FALSE, '', array());

var_dump(array_filter($a));
// array()

var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());

var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())

To sum up:

  • 0 or '0' will remove 0 and '0'
  • NULL, FALSE or '' will remove NULL, FALSE and ''
helpse
  • 1,518
  • 1
  • 18
  • 29
44
foreach($linksArray as $key => $link) 
{ 
    if($link === '') 
    { 
        unset($linksArray[$key]); 
    } 
} 
print_r($linksArray); 
rybo111
  • 12,240
  • 4
  • 61
  • 70
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 4
    A concise, readable and safe solution that doesn't remove `false` and `0`. Considering this was posted **the same minute** as the accepted answer (that is unsafe and incorrect), I can only assume your 8 upvotes compared to the accepted answer's 649 is down to the latter being a one-line solution. – rybo111 Feb 10 '16 at 16:27
  • @rybo111 - possibly, though using that logic in a callback to `array_filter()` would be a cleaner approach than a `foreach()` loop – Mark Baker Feb 10 '16 at 16:48
  • Perhaps quicker, but your solution is the most readable, which is important. For those using your solution requiring `trim()`, I would recommend `if(is_string($link) && trim($link) === '')` – rybo111 Feb 10 '16 at 17:16
36

In short:

This is my suggested code:

$myarray =  array_values(array_filter(array_map('trim', $myarray), 'strlen'));

Explanation:

I thinks use array_filter is good, but not enough, because values be like space and \n,... keep in the array and this is usually bad.

So I suggest you use mixture ‍‍array_filter and array_map.

array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed.

Samples:

$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");

// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);

// "a"
$new2 = array_filter(array_map('trim', $myarray));

// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');

// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));

var_dump($new1, $new2, $new3, $new4);

Results:

array(5) {
  [0]=>
" string(1) "
  [1]=>
  string(1) "
"
  [2]=>
  string(2) "
"
  [4]=>
  string(1) " "
  [6]=>
  string(1) "a"
}
array(1) {
  [6]=>
  string(1) "a"
}
array(2) {
  [5]=>
  string(1) "0"
  [6]=>
  string(1) "a"
}
array(2) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "a"
}

Online Test:

http://sandbox.onlinephpfunctions.com/code/e02f5d8795938be9f0fa6f4c17245a9bf8777404

Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
34

Another one liner to remove empty ("" empty string) elements from your array.

$array = array_filter($array, function($a) {return $a !== "";});

Note: This code deliberately keeps null, 0 and false elements.


Or maybe you want to trim your array elements first:

$array = array_filter($array, function($a) {
    return trim($a) !== "";
});

Note: This code also removes null and false elements.

marcovtwout
  • 5,230
  • 4
  • 36
  • 45
  • 3
    Exactly what I neeeded, and this is also compatible with [older PHPs](http://stackoverflow.com/questions/6485336/closures-or-create-function-in-php), thanks! ;-) – Stano Jul 11 '13 at 11:34
  • 1
    @JohnK Wrong. To do this exactly like the user whants to the callback **is** needed, unless you want to remove alzo zeroes and other falsey values. – Cranio Dec 10 '15 at 15:22
14

If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function:

array_values(array_filter($array));

Also see: PHP reindex array?

Community
  • 1
  • 1
Jacob Mulquin
  • 3,458
  • 1
  • 19
  • 22
14

The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here's a thorough explanation:

What does empty mean?

First of all, we must agree on what empty means. Do you mean to filter out:

  1. the empty strings only ("")?
  2. the strictly false values? ($element === false)
  3. the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...)
  4. the equivalent of PHP's empty() function?

How do you filter out the values

To filter out empty strings only:

$filtered = array_diff($originalArray, array(""));

To only filter out strictly false values, you must use a callback function:

$filtered = array_diff($originalArray, 'myCallback');
function myCallback($var) {
    return $var === false;
}

The callback is also useful for any combination in which you want to filter out the "falsey" values, except some. (For example, filter every null and false, etc, leaving only 0):

$filtered = array_filter($originalArray, 'myCallback');
function myCallback($var) {
    return ($var === 0 || $var === '0');
}

Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default:

$filtered = array_filter($originalArray);
Community
  • 1
  • 1
Cranio
  • 9,647
  • 4
  • 35
  • 55
  • 2
    If you want to take out `null` and `false`, but leave 0, you can also use php's built-in `strlen` function as your callback. – Cullub Jan 31 '16 at 00:16
11
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));

print_r($b)
user2511140
  • 1,658
  • 3
  • 26
  • 32
11

For multidimensional array

$data = array_map('array_filter', $data);
$data = array_filter($data);
HMagdy
  • 3,029
  • 33
  • 54
10

I had to do this in order to keep an array value of (string) 0

$url = array_filter($data, function ($value) {
  return (!empty($value) || $value === 0 || $value==='0');
});
rybo111
  • 12,240
  • 4
  • 61
  • 70
Matt
  • 1,328
  • 1
  • 16
  • 28
9
function trim_array($Array)
{
    foreach ($Array as $value) {
        if(trim($value) === '') {
            $index = array_search($value, $Array);
            unset($Array[$index]);
        }
    }
    return $Array;
}
step
  • 2,254
  • 2
  • 23
  • 45
ali Farmani
  • 91
  • 1
  • 2
9
$out_array = array_filter($input_array, function($item) 
{ 
    return !empty($item['key_of_array_to_check_whether_it_is_empty']); 
}
);
rybo111
  • 12,240
  • 4
  • 61
  • 70
Naitik Shah
  • 513
  • 6
  • 13
8

Just want to contribute an alternative to loops...also addressing gaps in keys...

In my case, I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.)

I was looking for something more like this: http://gotofritz.net/blog/howto/removing-empty-array-elements-php/

The combination of array_filter and array_slice does the trick.

$example = array_filter($example);
$example = array_slice($example,0);

No idea about efficiencies or benchmarks but it works.

Bhargav Variya
  • 725
  • 1
  • 10
  • 18
Chrisdigital
  • 384
  • 3
  • 8
  • 1
    I think array_values would have the same result as array_slice. That seems more intuitive in terms of reading the code later and understanding what it is doing. – arlomedia Mar 11 '15 at 17:15
7

I use the following script to remove empty elements from an array

for ($i=0; $i<$count($Array); $i++)
  {
    if (empty($Array[$i])) unset($Array[$i]);
  }
concept w
  • 71
  • 1
  • 1
6
$my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" ");   

foreach ($my as $key => $value) {
    if (is_null($value)) unset($my[$key]);
}

foreach ($my as $key => $value) {
    echo   $key . ':' . $value . '<br>';
} 

output

1:5

2:6

Kyslik
  • 8,217
  • 5
  • 54
  • 87
Naitik Shah
  • 513
  • 6
  • 13
5
foreach($arr as $key => $val){
   if (empty($val)) unset($arr[$key];
}
Robin van Baalen
  • 3,632
  • 2
  • 21
  • 35
Mak Ashtekar
  • 154
  • 1
  • 11
5

Just one line : Update (thanks to @suther):

$array_without_empty_values = array_filter($array);
Matt
  • 73
  • 1
  • 3
3

use array_filter function to remove empty values:

$linksArray = array_filter($linksArray);
print_r($linksArray);
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
Ankit Gupta
  • 189
  • 12
3

Remove empty array elements

function removeEmptyElements(&$element)
{
    if (is_array($element)) {
        if ($key = key($element)) {
            $element[$key] = array_filter($element);
        }

        if (count($element) != count($element, COUNT_RECURSIVE)) {
            $element = array_filter(current($element), __FUNCTION__);
        }

        return $element;
    } else {
        return empty($element) ? false : $element;
    }
}

$data = array(
    'horarios' => array(),
    'grupos' => array(
        '1A' => array(
            'Juan' => array(
                'calificaciones' => array(
                    'Matematicas' => 8,
                    'Español' => 5,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => 10,
                    'marzo' => '',
                )
            ),
            'Damian' => array(
                'calificaciones' => array(
                    'Matematicas' => 10,
                    'Español' => '',
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => '',
                    'marzo' => 5,
                )
            ),
        ),
        '1B' => array(
            'Mariana' => array(
                'calificaciones' => array(
                    'Matematicas' => null,
                    'Español' => 7,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => null,
                    'febrero' => 5,
                    'marzo' => 5,
                )
            ),
        ),
    )
);

$data = array_filter($data, 'removeEmptyElements');
var_dump($data);

¡it works!

iBet7o
  • 758
  • 8
  • 9
3

As per your method, you can just catch those elements in an another array and use that one like follows,

foreach($linksArray as $link){
   if(!empty($link)){
      $new_arr[] = $link
   }
}

print_r($new_arr);
Shahrukh Anwar
  • 2,544
  • 1
  • 24
  • 24
3

I think array_walk is much more suitable here

$linksArray = array('name', '        ', '  342', '0', 0.0, null, '', false);

array_walk($linksArray, function(&$v, $k) use (&$linksArray){
    $v = trim($v);
    if ($v == '')
        unset($linksArray[$k]);
});
print_r($linksArray);

Output:

Array
(
    [0] => name
    [2] => 342
    [3] => 0
    [4] => 0
)
  • We made sure that empty values are removed even if the user adds more than one space

  • We also trimmed empty spaces from the valid values

  • Finally, only (null), (Boolean False) and ('') will be considered empty strings

As for False it's ok to remove it, because AFAIK the user can't submit boolean values.

Rain
  • 3,416
  • 3
  • 24
  • 40
1

With these types of things, it's much better to be explicit about what you want and do not want.

It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer.

Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed.

In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.

Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop.

<?php

$xs = [0, 1, 2, 3, "0", "", false, null];

$xs = array_filter($xs, function($x) {
    if ($x === null) { return false; }
    if ($x === false) { return false; }
    if ($x === "") { return false; }
    if ($x === "0") { return false; }
    return true;
});

$xs = array_values($xs); // reindex array   

echo "<pre>";
var_export($xs);

Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.

See this example and the inline comments for the output.

<?php

/**
 * @param string $valueToFilter
 *
 * @return \Closure A function that expects a 1d array and returns an array
 *                  filtered of values matching $valueToFilter.
 */
function filterValue($valueToFilter)
{
    return function($xs) use ($valueToFilter) {
        return array_filter($xs, function($x) use ($valueToFilter) {
            return $x !== $valueToFilter;
        });
    };
}

// partially applied functions that each expect a 1d array of values
$filterNull = filterValue(null);
$filterFalse = filterValue(false);
$filterZeroString = filterValue("0");
$filterEmptyString = filterValue("");

$xs = [0, 1, 2, 3, null, false, "0", ""];

$xs = $filterNull($xs);        //=> [0, 1, 2, 3, false, "0", ""]
$xs = $filterFalse($xs);       //=> [0, 1, 2, 3, "0", ""]
$xs = $filterZeroString($xs);  //=> [0, 1, 2, 3, ""]
$xs = $filterEmptyString($xs); //=> [0, 1, 2, 3]

echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]

Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you.

<?php

/**
 * Supply between 1..n functions each with an arity of 1 (that is, accepts
 * one and only one argument). Versions prior to php 5.6 do not have the
 * variadic operator `...` and as such require the use of `func_get_args()` to
 * obtain the comma-delimited list of expressions provided via the argument
 * list on function call.
 *
 * Example - Call the function `pipe()` like:
 *
 *   pipe ($addOne, $multiplyByTwo);
 *
 * @return closure
 */
function pipe()
{
    $functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo]
    return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1
        return array_reduce( // chain the supplied `$arg` value through each function in the list of functions
            $functions, // an array of functions to reduce over the supplied `$arg` value
            function ($accumulator, $currFn) { // the reducer (a reducing function)
                return $currFn($accumulator);
            },
            $initialAccumulator
        );
    };
}

/**
 * @param string $valueToFilter
 *
 * @return \Closure A function that expects a 1d array and returns an array
 *                  filtered of values matching $valueToFilter.
 */
function filterValue($valueToFilter)
{
    return function($xs) use ($valueToFilter) {
        return array_filter($xs, function($x) use ($valueToFilter) {
            return $x !== $valueToFilter;
        });
    };
}

$filterer = pipe(
    filterValue(null),
    filterValue(false),
    filterValue("0"),
    filterValue("")
);

$xs = [0, 1, 2, 3, null, false, "0", ""];
$xs = $filterer($xs);

echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]
puiu
  • 726
  • 9
  • 18
0

try this ** **Example

$or = array(
        'PersonalInformation.first_name' => $this->request->data['User']['first_name'],
        'PersonalInformation.last_name' => $this->request->data['User']['last_name'],
        'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'],
        'PersonalInformation.dob' => $this->request->data['User']['dob'],
        'User.email' => $this->request->data['User']['email'],
    );



 $or = array_filter($or);

    $condition = array(
        'User.role' => array('U', 'P'),
        'User.user_status' => array('active', 'lead', 'inactive'),
        'OR' => $or
    );
Ashish Pathak
  • 827
  • 8
  • 16