I have an array of values that can be DISABLED or ENABLED, so I want to know how many are there ENABLED. Here is a piece of code:
$list = array(
$variable1,
$variable2,
$variable3,
$variable4
);
$count = count($list);
Thanks for any reply.
UPDATE: the values are NOT true and or false but ENABLE / DISABLE. Do your answers apply in this case? Thanks again.
If the only valid options are boolean TRUE and FALSE, then
$countTrue = array_sum($list);
EDIT
with 'ENABLE' and 'DISABLE' as the possible values:
$countTrue = array_reduce(
$list,
function($counter, $value) {
return $counter + ($value == 'ENABLE');
},
0
);
Just use array_filter
$list = array(true,false,true,true);
$count = count(array_filter($list));
echo $count ;
Or
$list = array("Enable","DISABLE","ENabLE","ENABLE");
$count = count(array_filter($list,function($v) { return stripos($v, "enable") !== false; } ));
echo $count ;
ENABLE and DISABLE are long string but they start with E & D respectively you can use that for counting
$count = array_reduce($list,function($a,$b){$b{0} == "E" and $a++ ;return $a;},0);
echo $count ;
They Would all output
3
$array = array('ENABLED', 'DISABLED', 'ENABLED', 'ENABLED', 'ENABLED', 'DISABLED');
$count = array_count_values($array);
would produce
array(2) {
["ENABLED"]=>int(4)
["DISABLED"]=>int(2)
}
so you can call it using
$count["ENABLED"]
Just iterate through the array and count them.
$trueValues = 0;
foreach ($list as $listItem)
{
if ($listItem)
$trueValues++;
}
echo "Array has ".$trueValues." TRUE items);
$list = array('ENABLE','DISABLE','ENABLE','ENABLE');
function countTrues($n)
{
if ($n == 'ENABLE'){return $n;}
}
$x = array_filter($list , "countTrues");
$count = count($x);
This should do the trick
Related
This question already has answers here:
Code after a return statement in a PHP function
(3 answers)
Closed 6 months ago.
please check my code. i have some program to return the third largest word in a given array.
if in the third largest word has a same letters long, so retrun the last one.
for example ['world', 'hello', 'before', 'all', 'dr'] the output should be 'hello'.
my program is working fine, however when I want to echo the $result, the code doesn't execute.
here is my code:
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "THIS RESULT SHOULD BE RE ASSIGNED, BUT WHY !!!!!";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
return $result;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
return $result;
}
}
echo "THIS LINE IS NOT WORKING";
echo $result;
You have to use break instead of return.
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
break;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
break;
}
}
echo $result;
Simply remove the return statements in the loop. instead of return, perhaps use break.
You can try this way as well.
<?php
/**
* Read more about here
* https://www.php.net/manual/en/function.usort.php
*/
function sort_by_length($a,$b){
return strlen($b)-strlen($a);
}
$array =['world', 'hello', 'before', 'all', 'dr'];
usort($array,'sort_by_length'); // sorting array with a custom function.
if(count($array) >= 2) {
$sliced = array_slice($array, 2);
$result = $sliced[0];
/**
* Read more at
* 1. https://www.php.net/manual/en/function.next.php
* 2. https://www.php.net/manual/en/function.current.php
*/
while(strlen(current($sliced)) == strlen(next($sliced))){
$result = current($sliced);
}
echo $result;
} else {
echo "Not enough items in array.";
}
This will output
hello
Remove the return .It return the value so any code after it will not be executed.
is there any way to check whether array_filter deleted any value from an array?
The solutions I've thought of are these ones:
$sample_array = ["values"];
$array_copy = $sample_array;
if (array_filter($sample_array, 'fn') === $array_copy) {
#Some value was deleted from the array
} else {
#The array was not modified
}
This one doesn't seem very efficient, as it has to copy the entire array.
$sample_array = ["values"];
$array_count = count($sample_array);
if (count(array_filter($sample_array, 'fn')) === $array_count) {
#The array was not modified
} else {
#Some value was deleted from the array
}
This one seems more efficient, though I was wondering if there was a more elegant way of approaching the issue.
Thank you beforehand.
You can extend your function to keep track of the change itself.
$array = [1, 2, 3, 4];
$changed = 0;
$new = array_filter($array, function($e) use (&$changed) {
$result = $e <= 2;
if(!$result) $changed++;
return $result;
});
Returns $changed as 2.
Use array_diff to compare two arrays.
if(array_diff($array_copy, $sample_array))
echo "not same";
Using 'count()' is IMHO the most elegant solution and, I suspect, may be a lot more efficient - you'd need to measure it. OTOH, for your consideration...
function fn($arg, $mode='default')
{
static $matched;
if ('default'==$mode) {
$result=real_filter_fn($arg);
$matched+=$result ? 1 : 0;
return $result;
}
$result=$matched;
$matched=0;
return $result;
}
If you want to keep track of the removed elements, you could do something like this.
$sample_array = ['values', 'test'];
$removed = []; // Contains all the removed values.
$new_array = array_filter($sample_array, function($value) use (&$removed) {
if($value == 'test') {
$removed[] = $value; // Adds the value to the removed array.
return false;
}
return true;
});
print_r($removed);
You could use a closure to change the state of a boolean variable:
$sample_array = [1,2,3,4];
$array_changed = false;
//Use closure to change $array_changed
print_r(array_filter($sample_array, function($var) use (&$array_changed) {
$check = (!($var & 1));
$array_changed = $array_changed?:$check;
return $check;
}));
if ($array_changed) {
#Some value was deleted from the array
} else {
#The array was not modified
}
[EDIT]
This is a simple speedtest of your solutions compared to mine:
/**********************SPEEDTEST**************************/
function fn ($var) {
return (!($var & 1));
}
$sample_array = [1,2,3,4];
$before = microtime(true);
for ($i=0 ; $i<100000 ; $i++) {
$array_changed = false;
//Use closure to change $array_changed
array_filter($sample_array, function($var) use (&$array_changed) {
$check = (!($var & 1));
$array_changed = $array_changed?:$check;
return $check;
});
if ($array_changed) {
#Some value was deleted from the array
} else {
#The array was not modified
}
}
$after = microtime(true);
echo "Using closure: " . ($after-$before)/$i . " sec/run\n";
echo '<br>';
/*******************************************************/
$before = microtime(true);
for ($i=0 ; $i<100000 ; $i++) {
$array_copy = $sample_array;
if (array_filter($sample_array, 'fn') === $array_copy) {
#Some value was deleted from the array
} else {
#The array was not modified
}
}
$after = microtime(true);
echo "Using array copy: " . ($after-$before)/$i . " sec/run\n";
echo '<br>';
/*******************************************************/
$before = microtime(true);
for ($i=0 ; $i<100000 ; $i++) {
$array_count = count($sample_array);
if (count(array_filter($sample_array, 'fn')) === $array_count) {
#The array was not modified
} else {
#Some value was deleted from the array
}
}
$after = microtime(true);
echo "Using array count: " . ($after-$before)/$i . " sec/run\n";
The results:
Using closure: 9.1402053833008E-7 sec/run
Using array copy: 4.9885988235474E-7 sec/run
Using array count: 5.5881977081299E-7 sec/run
Maybe that helps with decision-making :)
How to find max value from array when there is integer,string and special symbol in array without using inbuilt function in php ?
is_numeric is the PHP Built in method. If you don't want to use that then we have to type cast using (int) and check.
$arr = [1, 3, -10, 'string', true, [23]];
$max = null;
foreach($arr as $key => $val) {
if (is_numeric($val)) {
if ($max == null) {
$max = $val;
} else if ($val > $max) {
$max = $val;
}
}
}
Try to use this:
$maxs = array_keys($array, max($array));
Using this code you can find max value from an array:
$array = array('a','b',1,2,'$','^');
$max = $temp = 0;
//This loop is to get max value from array
for ($i = 0 ; $i < count($array); $i++) {
if ($i == 0) {
$max = $temp = $array[$i];
}
if ($i > 0) {
if ($array[$i] > $temp) {
$max = $array[$i];
}
}
}
print_r($max);
Since you can't do math to a string or Boolean value you could try math and if that fails it's not numeric.
$arr = [1, "BBB", 23, -10, 'str', true, false, 50, "#", "$"];
$max = 0;
Foreach ($arr as $v){
If(!#$v/1==0 && $v>$max) $max =$v;
}
Echo $max;
https://3v4l.org/Po31i
If you try "str"/1 you will get the result 0 and an error notice.
The # suppress the error.
Edit, forgot special symbol in array
I have an array like as
$arr[0] = 'summary';
$arr[1]['contact'][] = 'address1';
$arr[1]['contact'][] = 'address2';
$arr[1]['contact'][] = 'country';
$arr[1]['contact'][] = 'city';
$arr[1]['contact'][] = 'pincode';
$arr[1]['contact'][] = 'phone_no';
$arr[2]['work'][] = 'address1';
$arr[2]['work'][] = 'address2';
$arr[2]['work'][] = 'country';
$arr[2]['work'][] = 'city';
$arr[2]['work'][] = 'pincode';
$arr[2]['work'][] = 'phone_no';
Using count($arr) it returns 3 but I also need to count inner array values so it will return 13
What I've tried so far is
function getCount($arr,$count = 0) {
foreach ($arr as $value) {
if (is_array($value)) {
echo $count;
getCount($value,$count);
}
$count = $count+1;
}
return $count;
}
echo getCount($arr);
But its not working as expected
You can use array_walk_recursive for this. This may help -
$tot = 0;
array_walk_recursive($arr, function($x) use(&$tot) {
$tot++;
});
But It is a recursive function so you need to be careful about that.
In that getCount() method you are not storing the count of the array anywhere. So for every call $count is incremented by 1 only.
DEMO
Simply try this
function getCount($arr, $count = 0) {
foreach ($arr as $value) {
if (is_array($value)) {
$count = getCount($value, $count);
} else {
$count = $count + 1;
}
}
return $count;
}
echo getCount($arr);
What you were doing over here is that you were not storing the value within any variable and that is making an issues with your code as you were on the perfect way
If you need to count only the first two levels, you can do a simple foreach, no need to use a recursive function!:
$count = 0;
foreach( $bigArray as $smallArray ){
if( is_array( $smallArray ) )
$count += count( $smallArray );
else
$count ++;
}
Perhaps I am naive in my approach, but I simply use the sizeof() function. The function's documentation shows that it can take a second argument 1 to tell the function to recursively count multidimensional arrays.
So, to get the 'count' you could simply write sizeof($arr, 1); and it should return 13.
I recognize the value of writing your own function, but doesn't this built-in PHP method solve the problem quite succinctly?
Consider the following array.
$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 3;
$a['d'] = 4;
and then i am looping the array
foreach( $a as $q => $x )
{
# Some operations ....
if( isLastElement == false ){
#Want to do some more operation
}
}
How can i know that the current position is last or not ?
Thanks.
Take a key of last element & compare.
$last_key = end(array_keys($a));
foreach( $a as $q => $x )
{
# Some operations ....
if( $q == $last_key){
#Your last element
}
}
foreach (array_slice($a, 0, -1) as $q => $x) {
}
extraProcessing(array_slice($a, -1));
EDIT:
I guess the first array_slice is not necessary if you want to do the same processing on the last element. Actually neither is the last.
foreach ($a as $q => $x) {
}
extraProcessing($q, $x);
The last elements are still available after the loop.
You can use the end() function for this operation.
<?php
$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 3;
$a['d'] = 4;
$endkey= end(array_keys($a));
foreach( $a as $q => $x )
{
# Some operations ....
if( $endkey == $q ){
#Want to do some more operation
echo 'last key = '.$q.' and value ='.$x;
}
}
?>