There are multiple variables say $a,$b,$c,$d having boolean value.
So what i am trying to do is .
if($a){echo 1;}
if($b){echo 2;}
if($c){echo 3;}
if($d){echo 4;}
and so on.. 50 variables
is there any better way to do this?
Note: More than one variable can be true.
You can use this code to iterate :
$a= $b = $c = TRUE;
$array = array(0=> $a,1=>$b,2=> $c);
foreach($array as $key => $value){
if($value){
echo $key;
}
}
Maybe put all boolean variable inside an boolean array, and iterate the array to check the value
$boolArray = array();
$boolArray[0] = array($a, 1);
$boolArray[1] = array($b, 2);
$boolArray[2] = array($c, 3);
...
for($x = 0; $x < count($boolArray); $x++) {
if ($boolArray[x][1]) {
echo (string)$boolArray[x][2];
}
}
I think you're looking for something like this.
<?php
# Define the settings you already have
$a = true;
$b = true;
$c = true;
# Create an array with letters from a to z
# Instead of this, you can create an array of field names like array('a', 'b', 'c', 'd');
$options = range('a', 'z');
# Loop in the letters from above
foreach($options as $id => $letter) {
# Check if variable exists and boolean is true
if(isset(${$letter}) && ${$letter} === true) {
# Output number from id
echo $id + 1;
}
}
?>
Related
I want to check the longest side of an triangle:
The lenghts and the sides are saved in an array ($allSides)
Now I want to display the lagest side of all! I Want to check
the longest with an "foreach-action":
<?php
triangle(1, 5, 5);
function triangle($a, $b, $c) {
$allSides = array(
'a' => $a,
'b' => $b,
'c' => $c
);
if($a < $b + $c || $b < $a + $c || $c < $a + $b) {
echo " | Das Dreieck ist konstruierbar! <br>";
$U = $a + $b + $c;
echo " | Umfang: ".$U."<br>";
$longestSide = max($allSides);
$allSidesKeys = getSideKey($longestSide, $allSides);
$keys = implode(", ", $allSidesKeys);
echo "| Längste Seite(".$keys."): ".$longestSide."<br>";
} else {}
}
function getSideKey($longestSide, $allSides) {
$allSidesKeys = array();
foreach($allSides as $key => $value) {
echo $key.$value;
if($value == $longestSide) {
array_push($allSidesKeys, $key);
print_r($allSidesKeys);
return $allSidesKeys;
}
}
}
?>
But when I check, if the $value of the side (lenght) == to the longest side, the if
stops. And if there are 2 sides with the same lenght I want to display them TWO.
I want to save both of the sides with the same lenght in an array too.
You need to move return $allSidesKeys; outside of the if and for blocks. Otherwise it returns on the first match.
This is how your function will look like:
function getSideKey($longestSide, $allSides) {
$allSidesKeys = array();
foreach($allSides as $key => $value) {
echo $key.$value;
if($value == $longestSide) {
array_push($allSidesKeys, $key);
print_r($allSidesKeys);
}
}
return $allSidesKeys;
}
Its much easier. Just get the max as you have and then us array_keys to get the keys that have that value:
function triangle($a, $b, $c) {
$allSides = get_defined_vars();
$longestSide = max($allSides);
echo $longestSide . PHP_EOL;
$allSidesKeys = array_keys($allSides, $longestSide);
echo implode(',', $allSidesKeys) . PHP_EOL;
return $allSidesKeys;
}
$result = triangle(1, 5, 5);
Does php library have any function to check if all required fields are set in an array? For example:
function required_fields($vals,$required_fields_names){
for($i = 0; $i < count($required_fields_names); $i++){
if(!array_key_exists($required_fields_names[$i],$vals)){
return false
}
}
return true;
}
Is there already a native PHP function/method that does this?
array_difference is the closest built-in function for this:
function required_fields($vals,$required_fields_names){
$missing_fields = array_difference($required_fields_names, array_keys($vals));
return empty($missing_fields);
}
NO, there is no native method.
But you can improve that code.
<?php
function check_keys($keys,$array) {
foreach ($keys as $key) {
if(!array_key_exists($key, $array)) {
return false;
}
}
return true;
}
# Test Zone
$a = array('a' => 1,
'b' => 2,
'c' => 3);
$b = ['a','b','c'];
$c = ['a','b'];
$d = ['a','b','d'];
echo (int) check_keys($b,$a).'</br>'; # 1
echo (int) check_keys($c,$a).'</br>'; # 1
echo (int) check_keys($d,$a).'</br>'; # 0
?>
I need to find all combinations of items in several arrays with fixed subset size. For example, I have the 3 arrays :
$A = array('A1','A2','A3');
$B = array('B1','B2','B3');
$C = array('C1','C2','C3');
I want to generate combinations of size 2 from the above arrays. Like:
$Combinations = array(
[0] => array('A1', 'B1'),
[1] => array('A1', 'C1'),
[2] => array('A2', 'B1'),
[3] => array('A2', 'C1')
);
This solution is generating all combinations, but does not seem to have size parameter in it.
Looking for help!
$A = array('A1','A2','A3');
$B = array('B1','B2','B3');
$C = array('C1','C2','C3');
$All = array();
foreach ($A as $key1=>$value1){
foreach ($B as $key2=>$value2){
$All[] = array($value1,$value2 );
}
foreach ($C as $key3=>$value3){
$All[] = array($value1,$value3 );
}
}
print_r($All);
Check output here : https://eval.in/574060
Finally, found a solution. With the following script, you can combine any number of arrays with any number of elements per a combination. Please read the comments in the code and try to understand what happens.
<?php
$A = array('A1', 'A2', 'A3');
$B = array('B1', 'B2', 'B3');
$C = array('C1', 'C2', 'C3');
$combinationCount = 5;
$itemsPerCombination = 2;
$array = ['A', 'B', 'C'];
$combinations = array();
for ($x = 0; $x < $combinationCount; $x++) {
//to keep temporary names of arrays which come in a combination
$arrays = array();
for ($y = 0; $y < $itemsPerCombination; $y++) {
$valid = false;
while (!$valid) {
//get a random array, check if it is already in our selection
$arrayElement = $array[rand(0, count($array) - 1)];
if (in_array($arrayElement, $arrays)) {
$valid = false;
continue;
}
$arrays[] = $arrayElement;
$valid = true;
}
}
$found = false;
while (!$found) {
//for each selection in our selected arrays, take a random element and add to the combination.
$combination = array();
foreach ($arrays as $arr) {
$temp=$$arr;
$combination[] = $temp[rand(0, count($temp) - 1)];
}
if (in_array($combination, $combinations)) {
$found = false;
continue;
}
$combinations[] = $combination;
$found = true;
}
}
echo(json_encode($combinations));
?>
Example:
$a[] = '56';
$a[] = '66';
$a[] = '';
$a[] = '58';
$a[] = '85';
$a[] = '';
$a[] = '';
$a[] = '76';
$a[] = '';
$a[] = '57';
Actually how to find average value from this array excluding empty. please help to resolve this problem.
first you need to remove empty values, otherwise average will be not accurate.
so
$a = array_filter($a);
$average = array_sum($a)/count($a);
echo $average;
DEMO
More concise and recommended way
$a = array_filter($a);
if(count($a)) {
echo $average = array_sum($a)/count($a);
}
See here
The accepted answer works for the example values, but in general simply using array_filter($a) is probably not a good idea, because it will filter out any actual zero values as well as zero length strings.
Even '0' evaluates to false, so you should use a filter that explicitly excludes zero length strings.
$a = array_filter($a, function($x) { return $x !== ''; });
$average = array_sum($a) / count($a);
echo array_sum($a) / count(array_filter($a));
As a late look, item controls should be done with numeric check. Otherwise something like this $array = [1.2, 0.33, [123]] will corrupt the calculation:
// Get numerics only.
$array = array_filter($array, fn($v) => is_numeric($v));
// Get numerics only where value > 0.
$array = array_filter($array, fn($v) => is_numeric($v) && ($v > 0));
Finally:
public static function average(array $array, bool $includeEmpties = true): float
{
$array = array_filter($array, fn($v) => (
$includeEmpties ? is_numeric($v) : is_numeric($v) && ($v > 0)
));
return array_sum($array) / count($array);
}
Credits: froq.util.Arrays
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;
}
}
?>