I have an array in which I push true or false values. And I only want to execute the next function if the array is completely true or completely. But because they are not strings, I can not check it with in_array(...).
Does anybody know how I can check if an array is completely true or completely?
Greetings and Thank You! :D
$res = array_unique($array);
if(count($res) === 1 && $res[0]) {
// your code
}
First, check if all the array have same value
Then check if it's TRUE or false.
if(count(array_count_values($array))===1){
if($array[0]){
// Completely TRUE;
}else{
// Completely FALSE;
}
}
For PHP >= 7.4
To check if all items are true:
... = array_reduce($array, fn ($carry, $item) => $carry && $carry === $item, true);
To check if all items are false:
... = array_reduce($array, fn ($carry, $item) => $carry && $carry !== $item, true);
Related
I want to iterate through $student collection and multiply each value from $defaultValue and check whether it's less than or equal to the number I am getting from json data $jsonData->value. if any is less than $jsonData->value, will return true. But it is not returning anything ! why is that ? i have checked the code and found that, when i print $carry its not assigned as false. (according to this the default value of $carry is false). how to fix it ?
$jsonData = json_decode($request->data);
if ($jsonData->value!==0){
foreach ($array as $key => $data){
$lectures = Lecture::where('hall_id','=',$data['id'])->get();
foreach ($lectures as $lecture){
$student = Student::where('lecture_id','=',$lecture->id)
->where('date','>=',$jsonData->dateOne)
->where('date','<=',$jsonData->dateTwo)
->get();
$defaultValue = $lecture->value;
if (!$student ->isEmpty()){
$multiplied = collect($student )
->reduce(function($carry, $item) use ($defaultValue ,$jsonData){
return $carry || $item->number * $defaultValue <=$jsonData->value;
}, false);
}
}
}
$student returns
[{"id":2,"number ":10},{"id":79,"number ":1},{"id":9,"number ":4}]
$defaultValue reurns
2
$jsonData->value returns
10
Try this
$carry || (($item->number * $defaultValue) <=$jsonData->value);
I have a array that contain different keys and i want to filter the key based on the value TRUE OR FALSE.
I am in trouble please help.
Here is my code
foreach ($combine as $data) {
unset($data['user_name'], $data['date']);
if (array_values($data) == TRUE) {
pr(array_keys($data));
}
}
Here is the array
Array
(
[microsoft] => FALSE
[health_care] => TRUE
[nasa_cerification_type_i] => TRUE
[nasa_cerification_type_ii] => TRUE
[nasa_cerification_type_iii] => TRUE
)
I think this is what you want to do:
foreach($combine as $data){
unset($data['user_name'], $data['date']); //we don't need these
$valid = [];
foreach($data as $n => $v){
if($v === true){ //be careful! Are the values really boolean? then use ===, otherwise use ==
$valid[] = $n;
}
}
//do something with $valid
print_r($valid); //etc..
}
$trueArray=array_filter($array, function ($ar){
return ($ar==true);
});
$falseArray=array_filter($array, function ($ar){
return ($ar==false);
});
print_r($trueArray);
I have an array with boolean values, e.g.
$myarray = array(true, false, false, true, false);
Now I want to perform some logic operations on my array values, so I get the output:
FALSE
from my array.
You're trying to treat booleans as strings, which is fundamentally wrong. What you want is, for example, an array reduction:
$res = array_reduce($myarray, function ($a, $b) { return $a && $b; }, true);
// default value ^^^^
Or a more efficient short-circuiting all function:
function all(array $values) {
foreach ($values as $value) {
if (!$value) {
return false;
}
}
return true;
}
if (all($myarray)) ...
You could just search your array for false, and if it's present, return false, and if not return true:
$result = (array_search(false, $myarray, true) === false);
Since you edited your question, if you want it to return 0 or 1 just do:
$result = (array_search(false, $myarray, true) === false) ? 1 : 0;
You could try this:
$res = true;
foreach ($myarray as $item) $res &= $item;
echo var_dump($res);
A bit less elegant, but it should work. You'll have an integer in the end because we're using bit logic here, could be improved.
For a OR case you could do almost the same thing:
$res = true;
foreach ($myarray as $item) $res |= $item;
echo var_dump($res);
I'm writing a function named all to check all elements inside an array $arr, returning a single boolean value (based of $f return value). This is working fine passing custom functions (see the code with $gte0 been passed to all).
However sometimes one want just check that an array contains all true values: all(true, $arr) will not work becase true is passed as boolean (and true is not a function name). Does PHP have a native true() like function?
function all($f, array $arr)
{
return empty($arr) ? false : array_reduce($arr, function($v1, $v2) use ($f) {
return $f($v1) && $f($v2);
}, true);
}
$test = array(1, 6, 2);
$gte0 = function($v) { return $v >= 0; }
var_dump(all($gte0, $test)); // True
$test = array(true, true, false);
$id = function($v) { return $v; } // <-- this is what i would avoid
var_dump(all($id, $test)); // False
all(true, $test); // NOT WORKING because true is passed as boolean
all('true', $test); // NOT WORKING because true is not a function
EDIT: another way could be checking $f in all function:
$f = is_bool($f) ? ($f ? function($v) { return $v; }
: function($v) { return !$v; } ): $f;
After adding this, calling all with true is perfectly fine.
intval might do what you're looking for (especially as the array only contains integers in your example):
var_dump(all('intval', $test)); // False
However, many types to integer conversions are undefined in PHP and with float this will round towards zero, so this might not be what you want.
The more correct "function" would be the opposite of boolean true: empty, but it's not a function, so you can't use it (and invert the return value):
var_dump(!all('empty', $test)); // Does not work!
And there is no function called boolval or similar in PHP, so write it yourself if you need it ;)
Additionally your all function could be optimized. While iterating, if the current result is already FALSE, the end result will always be FALSE. And no need to call $f() n * 2 times anyway:
function all($f, array $arr)
{
$result = (bool) $arr;
foreach($arr as $v) if (!$f($v)) return FALSE;
return $result;
}
Edit: knittl is right pointing to array_filter, it converts to boolean with no function given which seems cool as there is no "boolval" function:
function all($f, array $arr)
{
return ($c = count($arr))
&& ($f ? $arr = array_map($f, $arr) : 1)
&& $c === count(array_filter($arr));
}
var_dump(all(0, $test)); // False
Making the first function parameter optional will do you a proper bool cast on each array element thanks to array_filter.
Better to pass in a function to map the values to booleans that you can then reduce to a final value.
function all($map, $data) {
if (empty($data)) { return false; }
$reduce = function($f, $n) {
return $f && $n;
};
return array_reduce(array_map($map, $data), $reduce, true);
}
$gte0 = function($v) { return $v >= 0; };
$gte2 = function($v) { return $v >= 2; };
$data = array(1, 2, 3, 4, 5);
var_dump(all($gte0, $data));
var_dump(all($gte2, $data));
Then the result of the function remains expectant but the test can be slotted in as needed. You can go a step further and allow both the map and reduce function to be passed in.
function mr($map, $reduce, $data) {
return array_reduce(array_map($map, $data), $reduce, true);
}
You could use PHP's array_filter function, it will remove all 'falsy' values from an array if no callback is specified:
$a = array ( true, true, false );
var_dump($a == array_filter($a));
There isn't any true() function in PHP, you should compare the value to true.
try
return ($f === $v1) && ($f === $v2);
instead of
return $f($v1) && $f($v2);
I think this should work:
function all($f, array $arr)
{
return empty($arr) ? false : array_reduce($arr, function($v1, $v2) use ($f) {
return $f($v1) && $f($v2);
}, true);
}
function isTrue($a)
{
return true === $a;
}
all("isTrue", $test);
I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function, that just performs a logical AND on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?
Why dont you just use
in_array — Checks if a value exists in an array
Example:
// creates an array with 10 booleans having the value true.
$array = array_fill(0, 10, TRUE);
// checking if it contains a boolean false
var_dump(in_array(FALSE, $array, TRUE)); // FALSE
// adding a boolean with the value false to the array
$array[] = FALSE;
// checking if it contains a boolean false now
var_dump(in_array(FALSE, $array, TRUE)); // TRUE
It would return true if all values are true, otherwise false.
Returns true if array is non empty and contains no false elements:
function array_and(arary $arr)
{
return $arr && array_reduce($arr, function($a, $b) { return $a && $b; }, true));
}
(Note that you would need strict comparison if you wanted to test against the false type.)
Am I over-engineering?
Yes, because you could use:
in_array(false, $arr, true);
There's nothing wrong with this in principle, as long as you don't AND all of the values indiscriminately; that is, you should terminate as soon as the first false is found:
function array_and(array $array)
{
foreach ($array as $value)
{
if (!$value)
{
return false;
}
}
return true;
}
you should be able to implement a small function that takes an array and iterates over it checking each member to see if it is false. Return a bool from the function based on the outcome of your checking....
Easy but ugly => O(N)
$a = array(1, 2, false, 5, 6, 'a');
$_there_is_a_false = false
foreach ($a as $b) {
$_there_is_a_false = !$b ? true : $_there_is_a_false;
}
another option: array-filter
Why not just use array_product()
$set = array(1,1,1,1,0,0);
$result = array_product($set);
Output: 0
AND Logical is essentially a multiplier.
1 * 1 = 1
1 * 0 = 0
0 * 1 = 0
0 * 0 = 0