Im looking for a way to remove empty elements from an array.
Im aware of array_filter() which removes all empty values.
The thing is that i consider a string containing nothing but spaces, tabs and newlines also to be empty.
So what is best used in this case?
Use trim() in callback for array_filter:
$array = array_filter($array, function ($v) { return (bool)trim($v); });
Or shorter version (with implicit type-casting):
$array = array_filter($array, 'trim');
php empty()
bool empty ( mixed $var )
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
Something like should do:
foreach($array as $key => $stuff)
{
if(empty(stuff))
{
unset($array[$key]);
}
}
$array = array_values($array );// to reinstate the numerical indexes.
I know this may be late to answer but it is for those who may have interest in other ways to solve this. It is my own way of doing it.
function my_array_filter($my_array)
{
$final_array = array();
foreach ( $my_array as $my_arr )
{
//check if array element is not empty
if (!empty($my_arr)) $final_array[] = $my_arr;
}
//remove duplicate elements
return array_unique( $final_array );
}
Hope someone finds this useful.
Related
I have an array as follows
[0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']]
I need to remove the elements with classId 2 or 4 from array and the expected result should be
[0=>['classId'=>3,'Name'=>'Doe']]
How will i achieve this without using a loop.Hope someone can help
You can use array_filter in conjunction with in_array.
$array = [0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']];
var_dump(
array_filter($array, function($item){return !in_array($item["classId"], [2,4]);})
);
Explanation
array_filter
Removes elements from the array if the call-back function returns false.
in_array
Searches an array for a value; returns boolean true/false if the value is (not)found.
Try this:
foreach array as $k => $v{
if ($v['classId'] == 2){
unset(array[$k]);
}
}
I just saw your edit, you could use array_filter like so:
function class_filter($arr){
return ($arr['classId'] == "whatever");
}
array_filter($arr, "class_filter");
Note: you'll still need to loop through a multi-dimensional array I believe.
I have an array thats got about 12 potential key/value pairs. That are based off a _POST/_GET
The keys are not numeric as in 0-n, and I need to retain the keys with there values where applicable. My issue is I know that on occasion a key will be passed where the value is null, empty, or equal to ''. In the event thats the case I want to trim out those keys before processing my array. As running down the line without something there is going to break my script.
Now a while back I either made or found this function (I don't remember which its been in my arsenal for a while, either way though).
function remove_array_empty_values($array, $remove_null_number = true)
{
$new_array = array();
$null_exceptions = array();
foreach($array as $key => $value)
{
$value = trim($value);
if($remove_null_number)
{
$null_exceptions[] = '0';
}
if(!in_array($value, $null_exceptions) && $value != "")
{
$new_array[] = $value;
}
}
return $new_array;
}
What I would love to do is very similar to this, however this works well with arrays that can have n-n key values and I am not dependent upon the key as well as the value to determine whats what where and when. As the above will just remove everything basically then just rebuilt the array. Where I am stuck is trying to figure out how to mimic the above function but where I retain the keys I need.
If I understand correctly what you're after, you can use array_filter() or you can do something like this:
foreach($myarray as $key=>$value)
{
if(is_null($value) || $value == '')
unset($myarray[$key]);
}
If you want a quick way to remove NULL, FALSE and Empty Strings (""), but leave values of 0 (zero), you can use the standard php function strlen as the callback function:
// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );
Source: http://php.net/manual/en/function.array-filter.php#111091
array_filter is a built-in function that does exactly what you need. At the most you will need to provide your own callback that decides which values stay and which get removed. The keys will be preserved automatically, as the function description states.
For example:
// This callback retains values equal to integer 0 or the string "0".
// If you also wanted to remove those, you would not even need a callback
// because that is the default behavior.
function filter_callback($val) {
$val = trim($val);
return $val != '';
}
$filtered = array_filter($original, 'filter_callback');
if you want to remove null, undifined, '', 0, '0', but don't remove string ' '
$result = array_filter( $array, 'ucfirst' );
Filtering the array for PHP 7.4 and above use this
// Filtering the array
$result = array_filter($array, fn($var) => ($var !== NULL && $var !== FALSE && $var !== ""));
use +1 with your key variable to skip null key in array
foreach($myarray as $key=>$value)
{
echo $key+1; //skip null key
}
Can someone help me figure out why I'm getting a syntax error with this function:
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
$array = array_values(unset($array[$j])); //error on this line says expected ;
return true;
break;
}
}
}
Any help most appreciated!
Jonesy
Remove array_values. It seems you just want to remove one value and unset is already doing the job:
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
unset($array[$j]);
return true;
}
}
}
More about unset.
Demo
Side note:
The code after a return is not executed anymore, so break is unnecessary.
$key is a misleading variable name here. Better would be $value.
Update: If you want to reindex the values of the array (in case you have a numeric array), you have to do it in two steps (as unset does not return a value):
unset($array[$j]);
$array = array_values($array);
Demo
You're trying to use the unset function inside array_values? What exactly are you expecting to happen here?
You should be able to just use:
unset($array[$j]);
As you've passed the array in by reference, this should be sufficient to remove it. No need to play with array values.
The problem is the unset. array_values expect an array as parameter, but unset does not have any return value.
I see what you're trying to do, I suggest you use this instead:
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
unset($array[$j]);
}
}
}
You don't actually need to return anything. unset is a void function.
Unset doesn't return anything:
void unset ( mixed $var [, mixed $var [, mixed $... ]] )
I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?
If you simply want to know if it exists, use in_array(), e.g.:
$exists = in_array("needle", $haystack);
If you want to know its corresponding key, use array_search(), e.g.:
$key = array_search("needle", $haystack);
// will return key for found value, or FALSE if not found
You can use PHP's in_array function to see if it exists, or array_search to see where it is.
Example:
$a = array('a'=>'dog', 'b'=>'fish');
in_array('dog', $a); //true
in_array('cat', $a); //false
array_search('dog', $a); //'a'
array_search('cat', $a); //false
Php inArray()
Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:
<?php
// $arr is the array to be searched, $needle the string to find.
// $found is true if the string is found, false otherwise.
$found = false;
foreach($arr as $key => $value) {
if($value == $needle) {
$found = true;
break;
}
}
?>
I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.
Here you go:
http://www.php.net/manual/en/function.array-search.php
The array_search function does exactly what you want.
$index = array_search("string to search for", $array);
Say we have this array:
<?php
$array = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
?>
If you want to check if the element 'foo' is in the array, you would do this
<?php
if(in_array('foo', $array)) {
// in array...
}else{
// not in array...
}
?>
If you want to get the array index of 'foo', you would do this:
<?php
$key = array_search('foo', $array);
?>
Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.
Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))