Remove empty values from PHP array but keep 0 - php

I have an array
array (size=7)
0 => string '2'
1 => string ''
2 => string ''
3 => string '0'
4 => string ''
5 => string ''
6 => string '2.5'
I used:-
array_filter()
to remove the null values and it returns
Array ( [0] => 2 [6] => 2 )
array_filter() removes null value and also '0' value.
Any builtin function is available in PHP to remove NULL values only.

Assumption: I think you want to remove NULL as well as empty-strings/values '' from your array. (What i understand from your desired output)
You have to use array_filter() with strlen()
array_filter($array,'strlen');
Output:-
https://eval.in/926585
https://eval.in/926595
https://eval.in/926602
Refrence:-
PHP: array_filter - Manual
PHP: strlen - Manual

Both 0 and '' are considered falsey in php, and so would be removed by array filter without a specific callback. The suggestion above to use 'strlen' is also wrong as it also remove an empty string which is not the same as NULL. To remove only NULL values as you asked, you can use a closure as the callback for array_filter() like this:
array_filter($array, function($v) { return !is_null($v); });

You can remove empty value and then re-index the array elements by using array_values() and array_filter() function together as such:
$arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0);
print_r(array_values(array_filter($arr)));
Output:
Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
)

function myFilter($var){
return ($var !== NULL && $var !== FALSE && $var !== '');
}
$res = array_filter($yourArray, 'myFilter');
If you just need the numeric values you can use is_numeric as your callback
Demo
$res = array_filter($values, 'is_numeric');

In case your array could contain line feeds and you want to filter them out as well, you may want to trim values first:
$arrayItems = ["\r", "\n", "\r\n", "", " ", "0", "a"];
$newArray = array_values(array_filter(array_map('trim', $arrayItems), 'strlen'));
// Output(newArray): ["0", "a"]
//Another great snippet to remove empty items from array
$newArray = array_filter($arrayItems , function ($item) {
return !preg_match('/^\\s*$/', $item);
// filter empty lines
});
// Output(newArray): ["0", "a"]
If you face any issue with implementing the code just comment here below.

As of PHP 7.4:
$withoutNulls = array_filter($withNulls, static fn($e) => $e !== null);

Remove null values from array
$array = array("apple", "", 2, null, -5, "orange", 10, false, "");
var_dump($array);
echo "<br>";
// Filtering the array
$result = array_filter($array);
var_dump($result);
?>

Related

How to see if an array of associative arrays is empty in php

I have a fairly easy issue where I need to see if an associative array of arrays is empty in php. My array looks like this:
array (
'person1' =>
array (
),
'person2' =>
array (
),
'person3' =>
array (
),
)
In my case, the three array's for the three people holds nothing so I need a test whether this is empty. I have done this which works:
if ( empty($form_values['person1']) && empty($form_values['person2']) && empty($form_values['person3'] ) ){
echo 'values empty!!';
}
But I was hoping something a bit more cleaner with using empty like the following:
if (empty( $form_values )) {
echo 'HI!';
}
You can use array_filter() to filter all of the empty array elements. You can then use empty to check if the result is empty then.
I've shorthanded the arrays so it's a easier to read since the arrays are empty. array() will work the same.
$form_values = [
'person1' => [],
'person2' => [],
'person3' => []
];
if (empty(array_filter($form_values))) {
// empty
} else {
// not empty
}
If you're looking for a one-liner then you could do something like:
$form_values = array (
'person1' =>
array (
),
'person2' =>
array (
),
'person3' =>
array (
),
);
if(array_sum(array_map(function($v){return !empty($v);}, $form_values)) === 0)
{
// empty
}
else
{
// not empty
}
Use a loop that tests each nested array. If none of them are non-empty, the whole array is empty.
$is_empty = true;
foreach ($form_values as $val) {
if (!empty($val)) {
$is_empty = false;
break;
}
}
<?php
$data =
[
'pig' => [],
'hog' => [],
'sow' => []
];
$all_empty = array_filter($data) === [];
var_dump($all_empty);
Output:
bool(true)
From the manual for array_filter:
If no callback is supplied, all empty entries of array will be
removed. See empty() for how PHP defines empty in this case.
Note that if an item was deemed as empty, like an empty string, it would still return true. This test may not be strict enough.
More explicitly:
if (array_filter($data, function($v) {return $v !== []; }) === []) {}
Filter out all items that aren't the empty array. What we'll be left with is an empty array if all items are an empty array.
Or search and compare:
if (array_keys($data, []) == array_keys($data)) {}
Check keys belonging to items containing the empty array match the keys of the array. Or rather all items (if they exist) are the empty array.
Note that an empty array will also satisfy the three solutions above.

PHP - preg_replace on an array not working as expected

I have a PHP array that looks like this..
Array
(
[0] => post: 746
[1] => post: 2
[2] => post: 84
)
I am trying to remove the post: from each item in the array and return one that looks like this...
Array
(
[0] => 746
[1] => 2
[2] => 84
)
I have attempted to use preg_replace like this...
$array = preg_replace('/^post: *([0-9]+)/', $array );
print_r($array);
But this is not working for me, how should I be doing this?
You've missed the second argument of preg_replace function, which is with what should replace the match, also your regex has small problem, here is the fixed version:
preg_replace('/^post:\s*([0-9]+)$/', '$1', $array );
Demo: https://3v4l.org/64fO6
You don't have a pattern for the replacement, or a empty string place holder.
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject)
Is what you are trying to do (there are other args, but they are optional).
$array = preg_replace('/post: /', '', $array );
Should do it.
<?php
$array=array("post: 746",
"post: 2",
"post: 84");
$array = preg_replace('/^post: /', '', $array );
print_r($array);
?>
Array
(
[0] => 746
[1] => 2
[2] => 84
)
You could do this without using a regex using array_map and substr to check the prefix and return the string without the prefix:
$items = [
"post: 674",
"post: 2",
"post: 84",
];
$result = array_map(function($x){
$prefix = "post: ";
if (substr($x, 0, strlen($prefix)) == $prefix) {
return substr($x, strlen($prefix));
}
return $x;
}, $items);
print_r($result);
Result:
Array
(
[0] => 674
[1] => 2
[2] => 84
)
There are many ways to do this that don't involve regular expressions, which are really not needed for breaking up a simple string like this.
For example:
<?php
$input = Array( 'post: 746', 'post: 2', 'post: 84');
$output = array_map(function ($n) {
$o = explode(': ', $n);
return (int)$o[1];
}, $input);
var_dump($output);
And here's another one that is probably even faster:
<?php
$input = Array( 'post: 746', 'post: 2', 'post: 84');
$output = array_map(function ($n) {
return (int)substr($n, strpos($n, ':')+1);
}, $input);
var_dump($output);
If you don't need integers in the output just remove the cast to int.
Or just use str_replace, which in many cases like this is a drop in replacement for preg_replace.
<?php
$input = Array( 'post: 746', 'post: 2', 'post: 84');
$output = str_replace('post: ', '', $input);
var_dump($output);
You can use array_map() to iterate the array then strip out any non-digital characters via filter_var() with FILTER_SANITIZE_NUMBER_INT or trim() with a "character mask" containing the six undesired characters.
You can also let preg_replace() do the iterating for you. Using preg_replace() offers the most brief syntax, but regular expressions are often slower than non-preg_ techniques and it may be overkill for your seemingly simple task.
Codes: (Demo)
$array = ["post: 746", "post: 2", "post: 84"];
// remove all non-integer characters
var_export(array_map(function($v){return filter_var($v, FILTER_SANITIZE_NUMBER_INT);}, $array));
// only necessary if you have elements with non-"post: " AND non-integer substrings
var_export(preg_replace('~^post: ~', '', $array));
// I shuffled the character mask to prove order doesn't matter
var_export(array_map(function($v){return trim($v, ': opst');}, $array));
Output: (from each technique is the same)
array (
0 => '746',
1 => '2',
2 => '84',
)
p.s. If anyone is going to entertain the idea of using explode() to create an array of each element then store the second element of the array as the new desired string (and I wouldn't go to such trouble) be sure to:
split on or : (colon, space) or even post: (post, colon, space) because splitting on : (colon only) forces you to tidy up the second element's leading space and
use explode()'s 3rd parameter (limit) and set it to 2 because logically, you don't need more than two elements

PHP: Turn array into string?

I have a problem: I need to turn an array into a string and pass it to a function for debugging output.
I cannot directly output the string with print_r, I need to join it with some other strings and pass it to a function.
Google did not bring any results that display the array in a human-readable way without directly printing them. I need a string which I can pass to another function.
You can use the print_r() function like this:
$myarray = ['a', 'b', 'c'];
$string = print_r($myarray, true);
echo $string;
The optional boolean flag as second parameters makes the function return a string instead of directly sending it to the output.
print_r uses an optional parameter to set to true to return the string instead of outputting it :
$array = array('foo', 'bar', array('baz' => true, 'test' => 42));
$stringifiedArray = print_r($array, true);
/* $stringifiedArray == "
Array
(
[0] => foo
[1] => bar
[2] => Array
(
[baz] => 1
[test] => 42
)
)
"
*/
Otherwise, I can see two ways, but both are not as easily readable by a human :
json_encode :
$stringifiedArray = json_encode($array, true);
// $stringifiedArray == "["foo","bar",{"baz":true,"test":42}]"
serialize :
$stringifiedArray = serialize($array, true);
// $stringifiedArray == "a:3:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;a:2:{s:3:"baz";b:1;s:4:"test";i:42;}}"
You could also try <?php implode(', ', $array); ?>

php loop over a array return always first element

easy question but i can't find a solution.
I have an array:
array
0 =>
array
1 => string '25' (length=2)
1 =>
array
1 => string '27' (length=2)
And i need to get:
array
0 => string '25' (length=2)
1 => string '27' (length=2)
Yea if course i could do:
foreach($result as $each) {
$resultIds[]=$each[1];
}
But i am pretty sure i saw this week somewhere a function for it something like...
array_something('current',$result);
What will loop over the array as foreach and return the first element so the result will be the same as the foreach solution. But i can't find it or remember it.
*What is the name of the function ? *
You can use array_map or array_walk
example of array_map
<?php
function first($n)
{
return $n[1];
}
$arr = array(
array(1, 2, 4),
array(1, 2, 3,),
);
var_export($arr);
// call internal function
$arr = array_map('current', $arr);
var_export($arr);
// call user function
$arr = array_map('first', $arr);
Please read manual here
$resultIds = array_map(function($arrEle) {
return $arrEle[0];
}, $result);
array_map takes a function which gets passed each of the elements of the array in turn, it is called for each array element.
The function then needs to return whatever you want in the new array, in this case you are wanting the second element of the child array so we return $arrEle[1];
after the whole array has been iterated over it returns the new array.

Re-order the array order both key and value

Say I've got an array
[0]=>test
[2]=>example.
I want o/p as
[0]=>test
[1]=>example
In my first array
[1]=>NULL
I've tried to remove this and reorder so, I used array_filter() to remove the null value.
Now, how do I reorder the array?
If I understand what you need, I think array_values should help (it will return only the values in the array, reindexed from 0):
print_r( array_values($arr) );
Here's an example of this: http://codepad.org/q7dVqyVY
You might want to use merge:
$newArray = array_merge(array(),$oldArray);
$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_values($Array);
or
$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_merge ($Array,array());
Credit goes to: http://www.codingforums.com/archive/index.php/t-17794.html.
<?php
$a = array(0 => 1, 1 => null, 2 => 3, 3 => 0);
$r = array_values(
array_filter($a, function ($elem)
{
if ( ! is_null($elem))
return true;
})
);
// output:
array (
0 => 1,
1 => 3,
2 => 0,
)
?>
NOTE: I am using an anonymous callback function for array_filter. Anonymous callback only works in php 5.3+ and is the appropriate in this case (IMHO). For previous versions of php just define it as normal.

Categories