How to count non-empty entries in a PHP array? - php

Consider:
[name] => Array ( [1] => name#1
[2] => name#2
[3] => name#3
[4] => name#4
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
)
$name = $_POST['name']
I want the result to be 4.
count ($name) = 9
count (isset($name)) = 1
count (!empty($name)) = 1
I would think that last one would accomplish what I need, but it is not (the empty entries are from unfilled inputs on the form).

You can use array_filter to only keep the values that are “truthy” in the array, like this:
array_filter($array);
If you explicitly want only non-empty, or if your filter function is more complex:
array_filter($array, function($x) { return !empty($x); });
# function(){} only works in in php >5.3, otherwise use create_function
So, to count only non-empty items, the same way as if you called empty(item) on each of them:
count(array_filter($array, function($x) { return !empty($x); }));
However, as empty() is only a shorthand for 'variable is set and the value is truthy', you don't really gain anything from that, because if your array contains values such as FALSE or "0", those would count as empty as well, same as with the plain call to array_filter.
The better way is to be explicit about what you want to count, e.g. if you want to exclude empty strings only, then use:
array_filter($array, function($x) { return ($x !== ""); });

count(array_filter($name));

Possible Solution: First you need to remove empty/null, false and zero values from an array and then count remaining values of an array
If you no need to remove zero values from an array, but remove null and false values
count(array_filter($arrayName, 'strlen'));
//"strlen" use as second parameter if you no need to remove zero '0' values
if you need to remove zero, null and false values from an array
count(array_filter($arrayName));

Here's a simple calculation function:
function non_empty(array $a) {
return array_sum(array_map(function($b) {return empty($b) ? 0 : 1;}, $a));
}
This will preserve array indexes if your form handling function needs them, like when you're associating the third input on name to the third value of another input set, and there are empty inputs in between them.

The easyest aproach is to use count() and array_filter() functions (eventually with an additional callback within array_filter() when we need type compatibility checking, but when the result of default empty() function is enough for us we don't need it).
However, we can also achieve that by using the array_reduce() function, and this approach is slightly more optimal in terms of computational complexity:
$initial = 0;
$count = array_reduce($arr, function($carry, $item) {
$carry += empty($item) ? 0 : 1;
return $carry;
}, $initial);
The $count variable counts all non-empty items in the array $arr.
Note that, the condition can be changed if someone wishes, e.g. instead of empty($item) we can use a stronger condition $item === '', etc.
When the array $arr is empty, $initial is returned.

Related

Remove array element by checking a value php

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.

PHP bug in array_udiff()?

function value_compare_func($a, $b){
if ($a === 'n_3') {
return 0;
}
return 1;
}
$array1 = array("n_1", "n_2", "n_3", "n_4" );
$array2 = array("green");
$result = array_udiff($array1, $array2, "value_compare_func");
print_r($result);
The expected output is:
Array([0] => 'n_1', [1] => 'n_2' , [3] => 'n_4' )
But PHP outputs:
Array([1] => 'n_2' , [3] => 'n_4' )
Where is n_1?
This is not a bug since you are not using the function as described in the docs.
The compare callback MUST compare $a and $b and decide if they are equals, to calculate the difference. The docs also states that you MUST return -1 and 1 to hint whether $a comes before $b; this may sound useless, but is probably used internally.
Your callback translate to something like: "every element comes after every other element, except when the first element is equal to 'n_3' in which case is equal to every other element". Well, it doesn't make sense, just like the result you get.
If you want to remove all element equals to 'n_3', just use array_filter. If you want to compare an array difference, then define a compare callback.

Return true elements from a Multi-checkbox true/ false array in php

I am quite bad at php. I have a Multicheckbox that outputs an array this way:
Array
(
[value1] => true
[value2] => false
[value2] => false
[value4] => false
[value5] => true
[value6] => false
)
I would like to return an array with only the elements (values) that are true. Then I will apply this:
$list_of_true_values = explode(',', $array_i_am_looking_for);
return $list_of_true_values;
As in the end I want to return this: value1,value5.
Thanks'
As Rajat has said you can use the array_keys() function. I'd also add that if you're looking to get an output of value1,value5, you shouldn't use explode(), but rather, it's duel, implode().
return implode(",", array_keys($array, true));
Is all you need.
As per your comment, if you'd like to wrap the keys in single quotes:
$keys = array_keys($array, true);
array_walk($keys, function(&$v, $k){$v = "'" . $v . "'";});
return (implode(",", $keys));
This is called Anonymous (Lambda) Syntax.
array_keys($array, true); will return array with keys with true value, which you need..
If you specifically have true/false values, you can use PHP's array_filter() without a callback:
$values = array_filter($_POST['data']);
Without a callback function, array_filter() will filter out all of the "false" and empty values. Then, to get the keys from the list obtained, you can then use PHP's array_keys() as only the ones with "true" values will be in the $values array:
return array_keys($values);
In your exact specification, using the optional $search_value parameter of array_keys() may suffice, as Rajat has shown in his answer. However, I would suggest using array_filter() if you ever need to extend the list of values you want to keep or discard.

How do I remove a specific key in an array using php?

I have an array with 4 values. I would like to remove the value at the 2nd position and then have the rest of the key's shift down one.
$b = array(123,456,789,123);
Before Removing the Key at the 2nd position:
Array ( [0] => 123 [1] => 456 [2] => 789 [3] => 123 )
After I would like the remaining keys to shift down one to fill in the space of the missing key
Array ( [0] => 123 [1] => 789 [2] => 123 )
I tried using unset() on the specific key, but it would not shift down the remaining keys. How do I remove a specific key in an array using php?
You need array_values($b) in order to re-key the array so the keys are sequential and numeric (starting at 0).
The following should do the trick:
$b = array(123,456,789,123);
unset($b[1]);
$b = array_values($b);
echo "<pre>"; print_r($b);
It is represented that your input data is an indexed array (there are no gaps in the sequence of the integer keys which start from zero). I'll compare the obvious techniques that directly deliver the desired result from the OP's sample data.
1. unset() then array_values()
unset($b[1]);
$b = array_value($b);
This is safe to use without checking for the existence of the index -- if missing, there will be no error.
unset() can receive multiple parameters, so if more elements need to be removed, then the number of function calls remains the same. e.g. unset($b[1], $b[3], $b[5]);
unset() cannot be nested inside of array_values() to form a one-liner because unset() modifies the variable and returns no value.
AFAIK, unset() is not particularly handy for removing elements using a dynamic whitelist/blacklist of keys.
2. array_splice()
array_splice($b, 1, 1);
// (input array, starting position, number of elements to remove)
This function is key-ignorant, it will target elements based on their position in the array. This is safe to use without checking for the existence of the position -- if missing, there will be no error.
array_splice() can remove a single element or, at best, remove multiple consecutive elements. If you need to remove non-consecutive elements you would need to make additional function calls.
array_splice() does not require an array_values() call because "Numerical keys in input are not preserved" -- this may or may not be desirable in certain situations.
3. array_filter() nested in array_values()
array_values(
array_filter(
$b,
function($k) {
return $k != 1;
},
ARRAY_FILTER_USE_KEY
)
)
This technique relies on a custom function call and a flag to tell the filter to iterate only the keys.
It will be a relatively poor performer because it will iterate all of the elements regardless of the logical necessity.
It is the most verbose of the options that I will discuss.
It further loses efficiency if you want to employ an in_array() call with a whitelist/blacklist of keys in the custom function.
Prior to PHP7.4, passing a whitelist/blacklist/variable into the custom function scope will require the use of use().
It can be written as a one-liner.
This is safe to use without checking for the existence of the index(es) -- if missing, there will be no error.
4. array_diff_key() nested in array_values()
array_values(
array_diff_key(
$b,
[1 => '']
)
);
This technique isn't terribly verbose, but it is a bit of an overkill if you only need to remove one element.
array_diff_key() really shines when there is a whitelist/blacklist array of keys (which may have a varying element count). PHP is very swift at processing keys, so this function is very efficient at the task that it was designed to do.
The values in the array which is declared as the second parameter of array_diff_key() are completely irrelevant -- they can be null or 999 or 'eleventeen' -- only the keys are respected.
array_diff_key() does not have any scoping challenges, compared to array_filter(), because there is no custom function called.
It can be written as a one-liner.
This is safe to use without checking for the existence of the index(es) -- if missing, there will be no error.
Use array_splice().
array_splice( $b, 1, 1 );
// $b == Array ( [0] => 123 [1] => 789 [2] => 123 )
No one has mentioned this, so i will do: sort() is your friend.
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach($fruits as $key => $val)
echo "fruits[$key] = $val";
output:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
// remove Lemon, too bitter
unset($fruits[2]);
// keep keys with asort
asort($fruits);
foreach($fruits as $key => $val)
echo "fruits[$key] = $val";
Output:
fruits[0] = apple
fruits[1] = banana
fruits[3] = orange
This is the one you want to use to reindex the keys:
// reindex keys with sort
sort($fruits);
foreach($fruits as $key => $val)
echo "fruits[$key] = $val";
Output:
fruits[0] = apple
fruits[1] = banana
fruits[2] = orange
If you want to remove an item from an array at a specific position, you can obtain the key for that position and then unset it:
$b = array(123,456,789,123);
$p = 2;
$a = array_keys($b);
if ($p < 0 || $p >= count($a))
{
throw new RuntimeException(sprintf('Position %d does not exists.', $p));
}
$k = $a[$p-1];
unset($b[$k]);
This works with any PHP array, regardless where the indexing starts or if strings are used for keys.
If you want to renumber the remaining array just use array_values:
$b = array_values($b);
Which will give you a zero-based, numerically indexed array.
If the original array is a zero-based, numerically indexed array as well (as in your question), you can skip the part about obtaining the key:
$b = array(123,456,789,123);
$p = 2;
if ($p < 0 || $p >= count($b))
{
throw new RuntimeException(sprintf('Position %d does not exists.', $p));
}
unset($b[$p-1]);
$b = array_values($b);
Or directly use array_splice which deals with offsets instead of keys and re-indexes the array (numeric keys in input are not preserved):
$b = array(123,456,789,123);
$p = 2;
if ($p < 0 || $p >= count($b))
{
throw new RuntimeException(sprintf('Position %d does not exists.', $p));
}
array_splice($b, $p-1, 1);

selecting an array key based on partial string

I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?
one solution i can think of:
foreach($myarray as $key=>$value){
if("show_me_" == substr($key,0,8)){
$number = substr($key,strrpos($key,'_'));
// do whatever you need to with $number...
}
}
I ran into a similar problem recently. This is what I came up with:
$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):
foreach($array as $k => $v)
{
if (strpos($k, 'show_me_') !== false)
{
$number = substr($k, strrpos($k, '_'));
}
}
However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)
to search for certain string in array keys you can use array_filter(); see docs
// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($key){
return(strpos($key,'search_') !== false);
},
// flag to let the array_filter(); know that you deal with array keys
ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);
if you search in the array values you can use the flag 0 or leave the flag empty
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
},
// flag to let the array_filter(); know that you deal with array value
0
);
or
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
}
);
if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value, $key){
return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
},
ARRAY_FILTER_USE_BOTH
);
in case you'll search for both you have to pass 2 arguments to the callback function
You can also use a preg_match based solution:
foreach($array as $str) {
if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
echo "Array element ",$str," matched and number = ",$m[1],"\n";
}
}
filter_array($array,function ($var){return(strpos($var,'searched_word')!==FALSE);},);
return array 'searched_key' => 'value assigned to the key'
foreach($myarray as $key=>$value)
if(count(explode('show_me_',$event_key)) > 1){
//if array key contains show_me_
}
More information (example):
if array key contain 'show_me_'
$example = explode('show_me_','show_me_120');
print_r($example)
Array ( [0] => [1] => 120 )
print_r(count($example))
2
print_r($example[1])
120

Categories