Related
Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:
foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);
But it doesn't work. $linksArray still has empty elements. I have also tried doing it with the empty() function, but the outcome is the same.
As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:
print_r(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));
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);
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');
$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
$myarray = array_filter($myarray, 'strlen'); //removes null values but leaves "0"
$myarray = array_filter($myarray); //removes all null values
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 ''
foreach($linksArray as $key => $link)
{
if($link === '')
{
unset($linksArray[$key]);
}
}
print_r($linksArray);
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
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.
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?
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:
the empty strings only ("")?
the strictly false values? ($element === false)
the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...)
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);
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));
print_r($b)
For multidimensional array
$data = array_map('array_filter', $data);
$data = array_filter($data);
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');
});
$out_array = array_filter($input_array, function($item)
{
return !empty($item['key_of_array_to_check_whether_it_is_empty']);
}
);
function trim_array($Array)
{
foreach ($Array as $value) {
if(trim($value) === '') {
$index = array_search($value, $Array);
unset($Array[$index]);
}
}
return $Array;
}
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.
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]);
}
$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
foreach($arr as $key => $val){
if (empty($val)) unset($arr[$key];
}
Just one line :
Update (thanks to #suther):
$array_without_empty_values = array_filter($array);
use array_filter function to remove empty values:
$linksArray = array_filter($linksArray);
print_r($linksArray);
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!
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);
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.
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]
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
);
Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:
foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);
But it doesn't work. $linksArray still has empty elements. I have also tried doing it with the empty() function, but the outcome is the same.
As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:
print_r(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));
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);
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');
$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
$myarray = array_filter($myarray, 'strlen'); //removes null values but leaves "0"
$myarray = array_filter($myarray); //removes all null values
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 ''
foreach($linksArray as $key => $link)
{
if($link === '')
{
unset($linksArray[$key]);
}
}
print_r($linksArray);
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
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.
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?
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:
the empty strings only ("")?
the strictly false values? ($element === false)
the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...)
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);
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));
print_r($b)
For multidimensional array
$data = array_map('array_filter', $data);
$data = array_filter($data);
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');
});
$out_array = array_filter($input_array, function($item)
{
return !empty($item['key_of_array_to_check_whether_it_is_empty']);
}
);
function trim_array($Array)
{
foreach ($Array as $value) {
if(trim($value) === '') {
$index = array_search($value, $Array);
unset($Array[$index]);
}
}
return $Array;
}
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.
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]);
}
$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
foreach($arr as $key => $val){
if (empty($val)) unset($arr[$key];
}
Just one line :
Update (thanks to #suther):
$array_without_empty_values = array_filter($array);
use array_filter function to remove empty values:
$linksArray = array_filter($linksArray);
print_r($linksArray);
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!
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);
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.
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]
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
);
This question already has answers here:
Remove empty array elements
(27 answers)
Closed 9 years ago.
I have an array
Array ( [0] => 0 [1] => [2] => 3 [3] => )
i want to remove null values from this and the result should be like this
Array ( [0] => 0 [1] => 3)
i don't want to remove 0 value from array.
this will do the trick:
array_filter($arr, static function($var){return $var !== null;} );
Code Example: https://3v4l.org/jtQa2
for older versions (php<5.3):
function is_not_null ($var) { return !is_null($var); }
$filtered = array_filter($arr, 'is_not_null');
Code Example: http://3v4l.org/CKrYO
You can use array_filter() which will get rid of the null empty values from the array
print_r(array_filter($arr, 'strlen'));
You can just loop through it.
<?php
foreach ($array as $i=>$row) {
if ($row === null)
unset($array[$i]);
}
CodePad
If you want to reindex the array to remove gaps between keys, you can just use a new array:
<?php
$array2 = array();
foreach ($array as $row) {
if ($row !== null)
$array2[] = $row;
}
$array = $array2;
CodePad
You are in a world of trouble now, because it is not too easy to distinguish null from 0 from false from "" from 0.0. But don't worry, it is solvable:
$result = array_filter( $array, 'strlen' );
Which is horrible by itself, but seems to work.
EDIT:
This is bad advice, because the trick leans on a strange corner case:
strlen(0) will be strlen("0") -> 1, thus true
strlen(NULL) will be strlen("")->0, thus false
strlen("") will be strlen(("")->0, thus false
etc.
The way you should do it is something like this:
$my_array = array(2, "a", null, 2.5, NULL, 0, "", 8);
function is_notnull($v) {
return !is_null($v);
}
print_r(array_filter($my_array, "is_notnull"));
This is well readable.
<?php
$arr = array( 0 => 0, 1=>null, 2=>3, 3=>null);
foreach ($arr as $key=>$val) {
if ($val === null)
unset($arr[$key]);
}
$new_arr = array_values($arr);
print_r($new_arr);
?>
Out put:
Array
(
[0] => 0
[1] => 3
)
simply
$keys=array_keys($yourArray,NULL);
if(!empty($keys))
{
foreach($keys as $key)
{
unset($yourArray[$key]);
}
}
var_dump($yourarray);
This question already has answers here:
Get min and max value in PHP Array
(9 answers)
Closed 2 years ago.
The Problem
I have a multidimensional array similar to the one below. What I'm trying to achieve is a way to find and retrieve from the array the one with the highest "Total" value, now I know there's a function called max but that doesn't work with a multidimensional array like this.
What I've thought about doing is creating a foreach loop and building a new array with only the totals, then using max to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I'm not sure that's the most efficient way either.
Any ideas?
Array
(
[0] => Array
(
[Key1] => Key1
[Total] => 13
)
[1] => Array
(
[Key2] => Key2
[Total] => 117
)
[2] => Array
(
[Key3] => Key3
[Total] => 39
)
)
Since PHP 5.5 you can use array_column to get an array of values for specific key, and max it.
max(array_column($array, 'Total'))
Just do a simple loop and compare values or use array_reduce. # is an error suppressor; it hides the fact that $a['total'] is not declared before it is accessed on the first iteration. Demo
$data = array_reduce($data, function ($a, $b) {
return #$a['Total'] > $b['Total'] ? $a : $b ;
});
print_r($data);
// Array( [Key2] => Key2 [Total] => 117 )
It could also be written with arrow function syntax which has been avaiable since PHP7.4. Demo
var_export(
array_reduce(
$data,
fn($result, $row) =>
$result['Total'] > $row['Total']
? $result
: $row,
['Key1' => null, 'Total' => PHP_INT_MIN]
)
);
// array ('Key2' => 'Key2', 'Total' => 117,)
It's so basic algorithm.
$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;
foreach($arr as $k=>$v)
{
if($v['Total']>$max)
{
$max = $v['Total'];
$found_item = $v;
}
}
echo "max value is $max";
print_r($found_item);
Working demo
I know this question is old, but I'm providing the following answer in response to another question that pointed here after being marked as a duplicate. This is another alternative I don't see mentioned in the current answers.
I know there's a function called max but that doesn't work with a multidimensional array like this.
You can get around that with array_column which makes getting the maximum value very easy:
$arr = [['message_id' => 1,
'points' => 3],
['message_id' => 2,
'points' => 2],
['message_id' => 3,
'points' => 2]];
// max value
$max = max(array_column($arr, 'points'));
Getting the associative key is where it gets a little more tricky, considering that you might actually want multiple keys (if $max matches more than one value). You can do this with an anonymous function inside array_map, and use array_filter to remove the null values:
// keys of max value
$keys = array_filter(array_map(function ($arr) use ($max) {
return $arr['points'] == $max ? $arr['message_id'] : null;
}, $arr));
Output:
array(1) {
[0]=>
int(1)
}
If you do end up with multiples keys but are only interested in the first match found, then simply reference $keys[0].
another simple method will be
$max = array_map( function( $arr ) {
global $last;
return (int)( ( $arr["Total"] > $last ) ? $arr["Total"] : $last );
}, $array );
print_r( max( $max ) );
<?php
$myarray = array(
0 => array(
'Key1' => 'Key1',
'Total' => 13,
),
1 => array(
'Key2' => 'Key2',
'Total' => 117,
),
2 => array(
'Key2' => 'Key3',
'Total' => 39,
),
);
$out = array();
foreach ($myarray as $item) {
$out[] = $item['Total'];
}
echo max($out); //117
unset($out, $item);
Can be done using array_walk(array_walk_recursive if needed)
$arr is the array you want to search in
$largestElement = null;
array_walk($arr, function(&$item, $key) use (&$largestElement) {
if (!is_array($largestElement) || $largestElement["Total"] < $item["Total"]) {
$largestElement = $item;
}
});
You can use php usort function:
http://php.net/manual/en/function.usort.php
A pretty illustrative example is given here:
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
So it will sort the max value to the last array index.
Output:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
This example is given on aforementioned link
array_reduce accepts a 3rd "initial" parameter. Use this to avoid the bad practice of using "#" error suppression :
$data = array_reduce($data, function ($a, $b) {
return $a['Total'] > $b['Total'] ? $a : $b ;
},['Total' => 0]);
print_r($data);
PHP 7.4
$data = array_reduce($data, fn(a,b) => $a['Total'] > $b['Total'] ? $a : $b, ['Total' => 0]);
Lets say I have this array:
$array = array('a'=>1,'z'=>2,'d'=>4);
Later in the script, I want to add the value 'c'=>3 before 'z'. How can I do this?
Yes, the order is important. When I run a foreach() through the array, I do NOT want this newly added value added to the end of the array. I am getting this array from a mysql_fetch_assoc()
The keys I used above are placeholders. Using ksort() will not achieve what I want.
http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler.
Take a sample db table with about 30 columns. I get this data using mysql_fetch_assoc(). In this new array, after column 'pizza' and 'drink', I want to add a new column 'full_dinner' that combines the values of 'pizza' and 'drink' so that when I run a foreach() on the said array, 'full_dinner' comes directly after 'drink'
Am I missing something?
$key = 'z';
$offset = array_search($key, array_keys($array));
$result = array_merge
(
array_slice($array, 0, $offset),
array('c' => 3),
array_slice($array, $offset, null)
);
Handling of nonexistent keys (appending $data by default):
function insertBeforeKey($array, $key, $data = null)
{
if (($offset = array_search($key, array_keys($array))) === false) // if the key doesn't exist
{
$offset = 0; // should we prepend $array with $data?
$offset = count($array); // or should we append $array with $data? lets pick this one...
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
Demo:
$array = array('a' => 1, 'z' => 2, 'd' => 4);
// array(4) { ["a"]=> int(1) ["c"]=> int(3) ["z"]=> int(2) ["d"]=> int(4) }
var_dump(insertBeforeKey($array, 'z', array('c' => 3)));
// array(4) { ["a"]=> int(1) ["z"]=> int(2) ["d"]=> int(4) ["c"]=> int(3) }
var_dump(insertBeforeKey($array, 'y', array('c' => 3)));
A simple approach to this is to iterate through the original array, constructing a new one as you go:
function InsertBeforeKey( $originalArray, $originalKey, $insertKey, $insertValue ) {
$newArray = array();
$inserted = false;
foreach( $originalArray as $key => $value ) {
if( !$inserted && $key === $originalKey ) {
$newArray[ $insertKey ] = $insertValue;
$inserted = true;
}
$newArray[ $key ] = $value;
}
return $newArray;
}
Then simply call
$array = InsertBeforeKey( $array, 'd', 'c', 3 );
According to your original question the best answer I can find is this:
$a = array('a'=>1,'z'=>2,'d'=>4);
$splitIndex = array_search('z', array_keys($a));
$b = array_merge(
array_slice($a, 0, $splitIndex),
array('c' => 3),
array_slice($a, $splitIndex)
);
var_dump($b);
array(4) {
["a"]=>
int(1)
["c"]=>
int(3)
["z"]=>
int(2)
["d"]=>
int(4)
}
Depending on how big your arrays are you will duplicate quite some data in internal memory, regardless if you use this solution or another.
Furthermore your fifth edit seems to indicate that alternatively your SQL query could be improved. What you seem to want to do there would be something like this:
SELECT a, b, CONCAT(a, ' ', b) AS ab FROM ... WHERE ...
If changing your SELECT statement could make the PHP solution redundant, you should definitely go with the modified SQL.
function insertValue($oldArray, $newKey, $newValue, $followingKey) {
$newArray = array ();
foreach (array_keys($oldArray) as $k) {
if ($k == $followingKey)
$newArray[$newKey] = $newValue;
$newArray[$k] = $oldArray [$k];
}
return $newArray;
}
You call it as
insertValue($array, 'c', '3', 'z')
As for Edit 5:
edit your sql, so that it reads
SELECT ..., pizza, drink, pizza+drink as full_meal, ... FROM ....
and you have the column automatically:
Array (
...
'pizza' => 12,
'drink' => 5,
'full_meal' => 17,
...
)
Associative arrays are not ordered, so you can simply add with $array['c'] = 3.
If order is important, one option is switch to a data structure more like:
$array = array(
array('a' => 1),
array('b' => 2)
array('d' => 4)
);
Then, use array_splice($array, 2, 0, array('c' => 3)) to insert at position 2. See manual on array_splice.
An alternative approach is to supplement the associative array structure with an ordered index that determines the iterative order of keys. For instance:
$index = array('a','b','d');
// Add new value and update index
$array['c'] = 3;
array_splice($index, 2, 0, 'c');
// Iterate the array in order
foreach $index as $key {
$value = $array[$key];
}
You can define your own sortmap when doing a bubble-sort by key. It's probably not terribly efficient but it works.
<pre>
<?php
$array = array('a'=>1,'z'=>2,'d'=>4);
$array['c'] = 3;
print_r( $array );
uksort( $array, 'sorter' );
print_r( $array );
function sorter( $a, $b )
{
static $ordinality = array(
'a' => 1
, 'c' => 2
, 'z' => 3
, 'd' => 4
);
return $ordinality[$a] - $ordinality[$b];
}
?>
</pre>
Here's an approach based on ArrayObject using this same concept
$array = new CitizenArray( array('a'=>1,'z'=>2,'d'=>4) );
$array['c'] = 3;
foreach ( $array as $key => $value )
{
echo "$key: $value <br>";
}
class CitizenArray extends ArrayObject
{
static protected $ordinality = array(
'a' => 1
, 'c' => 2
, 'z' => 3
, 'd' => 4
);
function offsetSet( $key, $value )
{
parent::offsetSet( $key, $value );
$this->uksort( array( $this, 'sorter' ) );
}
function sorter( $a, $b )
{
return self::$ordinality[$a] - self::$ordinality[$b];
}
}
For the moment the best i can found to try to minimize the creation of new arrays are these two functions :
the first one try to replace value into the original array and the second one return a new array.
// replace value into the original array
function insert_key_before_inplace(&$base, $beforeKey, $newKey, $value) {
$index = 0;
foreach($base as $key => $val) {
if ($key==$beforeKey) break;
$index++;
}
$end = array_splice($base, $index, count($base)-$index);
$base[$newKey] = $value;
foreach($end as $key => $val) $base[$key] = $val;
}
$array = array('a'=>1,'z'=>2,'d'=>4);
insert_key_before_inplace($array, 'z', 'c', 3);
var_export($array); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
// create new array
function insert_key_before($base, $beforeKey, $newKey, $value) {
$index = 0;
foreach($base as $key => $val) {
if ($key==$beforeKey) break;
$index++;
}
$end = array_splice($base, $index, count($base)-$index);
$base[$newKey] = $value;
return $base+$end;
}
$array = array('a'=>1,'z'=>2,'d'=>4);
$newArray=insert_key_before($array, 'z', 'c', 3);
var_export($array); // ( 'a' => 1, 'z' => 2, 'd' => 4, )
var_export($newArray); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
function putarrayelement(&$array, $arrayobject, $elementposition, $value = null) {
$count = 0;
$return = array();
foreach ($array as $k => $v) {
if ($count == $elementposition) {
if (!$value) {
$value = $count;
}
$return[$value] = $arrayobject;
$inserted = true;
}
$return[$k] = $v;
$count++;
}
if (!$value) {
$value = $count;
}
if (!$inserted){
$return[$value];
}
$array = $return;
return $array;
}
$array = array('a' => 1, 'z' => 2, 'd' => 4);
putarrayelement($array, '3', 1, 'c');
print_r($array);
Great usage of array functions but how about this as a simpler way:
Add a static column to the SQL and then replace it in the resultant array. Order stays the same:
SQL :
Select pizza , drink , 'pizza-drink' as 'pizza-drink' , 28 columns..... From Table
Array :
$result['pizza-drink'] = $result['pizza'] . $result['drink'];
A simplified Alix Axel function if you need to just insert data in nth position:
function array_middle_push( array $array, int $position, array $data ): array {
return array_merge( array_slice( $array, 0, $position ), $data, array_slice( $array, $position ) );
}
Try this
$array['c']=3;
An associative array is not ordered by default, but if you wanted to sort them alphabetically you could use ksort() to sort the array by it's key.
If you check out the PHP article for ksort() you will se it's easy to sort an array by its key, for example:
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
// The above example will output:
a = orange
b = banana
c = apple
d = lemon
you can add it by doing
$array['c']=3;
and if you absolutely want it sorted for printing purposes, you can use php's ksort($array) function
if the keys are not sortable by ksort, then you will have to create your own sort by using php's uasort function. see examples here
http://php.net/manual/en/function.uasort.php