Optimisation exercise in PHP - php

I am trying to automatically fill in a form with '0' if there is no value supplied. There are 14 questions to be filled in. The code I've written is ugly but works. I am looking to improve it by setting an array with all the questions and loop the command untill all the boxes are filled in with values or 0.
if ($q1 == '') {
$q1 = '0';
}
if ($q2 == '') {
$q2 = '0';
}
if ($q3 == '') {
$q3 = '0';
}
if ($q4 == '') {
$q4 = '0';
}
//... and so on up to $q14
if ($q13 == '') {
$q13 = '0';
}
if ($q14 == '') {
$q14 = '0';
}

Ideally, you should be using an array for these variables. Then you could simply loop through the indexes of the array to test and change as required. If you cannot change that, you can use variable variables to simplify the code:
for ($i = 1; $i <= 14; $i++) {
if (${"q$i"} == '') ${"q$i"} = 0;
}
If you do put the values in an array, you can loop through it with a foreach. Note the use of &$v to allow us to change the value in the loop:
foreach ($q as &$v) {
if ($v == '') $v = 0;
}
Demo on 3v4l.org

Related

How to do addition between two dropdown menus containing 1-5?

This is the code I have so far. I'm trying to use two dropdown menus in my HTML form that contains a 1-5 each and simply add them using POST.
//action for dropdown menu addition
$dropdownValueA = $_POST["dropdown1"];
$dropdownValueB = $_POST["dropdown2"];
$valueone = 0;
$valuetwo = 0;
if ($dropdownValueA == "1a"){
$valueone = 1;
}
if ($dropdownValueA == "2a"){
$valueone = 2;
}
if ($dropdownValueA == "3a"){
$valueone = 3;
}
if ($dropdownValueA == "4a"){
$valueone = 4;
}
if ($dropdownValueA == "5a"){
$valueone = 5;
}
if ($dropdownValueB == "1b"){
$valuetwo = 1;
}
if ($dropdownValueB == "2b"){
$valuetwo = 2;
}
if ($dropdownValueB == "3b"){
$valuetwo = 3;
}
if ($dropdownValueB == "4b"){
$valuetwo = 4;
}
if ($dropdownValueB == "5b"){
$valuetwo = 5;
}
echo $valueone + $valuetwo;
It's totally not clear what is your problem and what is not works as expected. But your code is... not good :) Maybe try something like
if( preg_match('/^([1-5])a$/', $dropdownValueA, $m) ) {
$valueone = $m[1];
}
if( preg_match('/^([1-5])b$/', $dropdownValueA, $m) ) {
$valuetwo = $m[1];
}
echo (int)$valueone + (int)$valuetwo;
If the numbers will always come first, this will be your best option.
$dropdownValueA = $_POST["dropdown1"];
$dropdownValueB = $_POST["dropdown2"];
$valueone = intval($dropdownValueA);
$valuetwo = intval($dropdownValueB);
echo $valueone + $valuetwo;
3v4l HERE

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

PHP evaluating the content of an array

I am trying to evaluate the content of an array. The array contain water temperatures submitted by a user.
The user submits 2 temperaures, one for hot water and one for cold water.
What I need is to evaluate both array items to find if they are within the limits, the limits are "Hot water: between 50 and 66", "Cold water less than 21".
If either Hot or Cold fail the check flag the Status "1" or if they both pass the check flag Status "0".
Below is the code I am working with:
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray new(array);
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$field = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val > $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
My question is:
When I run the script the array key(0) works but when the array key(1) is evaluted the status flag for key(1) overrides the status flag for key0.
If anyone can help that would be great.
Many thanks for your time.
It seems OK to me, exept for the values at limit, and you can simplify
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray = array("58", "21");
$Status = array() ;
foreach($SeqWaterArray as $key => $val) {
if($key == 0) {
$Status = ($val >= $row_WaterTemp['HotMin'] && $val <= $row_WaterTemp['Hotmax']) ;
$WaterHot = $val;
} else if($key == 1) {
$Status += ($val >= $row_WaterTemp['ColdMax']) ;
$WaterCold = $val;
}
}
If one fails, $Status = 1, if the two tests failed, $Status = 2, if it's ok, $Status = 0.
<?php
// this function return BOOL (true/false) when the condition is met
function isBetween($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
$coldMax = 20; $hotMin = 50; $hotMax = 66;
// I decided to simulate a test of more cases:
$SeqWaterArray['john'] = array(58, 30);
$SeqWaterArray['martin'] = array(34, 15);
$SeqWaterArray['barbara'] = array(52, 10);
foreach($SeqWaterArray as $key => $range) {
$flag = array();
foreach($range as $type => $temperature) {
// here we fill number 1 if the temperature is in range
if ($type == 0) {
$flag['hot'] = (isBetween($temperature, $hotMin, $hotMax) ? 0 : 1);
} else {
$flag['cold'] = (isBetween($temperature, 0, $coldMax) ? 0 : 1);
}
}
$results[$key]['flag'] = $flag;
}
var_dump($results);
?>
This is the result:
["john"]=>
"flag"=>
["hot"]=> 1
["cold"]=> 0
["martin"]=>
"flag" =>
["hot"]=> 1
["cold"]=> 0
["barbara"]=>
"flag" =>
["hot"]=> 0
["cold"]=> 0
I don't think that you need a foreach loop here since you are working with a simple array and apparently you know that the first element is the hot water temperature and the second element is the cold water temperature. I would just do something like this:
$row_WaterTemp['HotMin'] = 50;
$row_WaterTemp['HotMax'] = 66;
$row_WaterTemp['ColdMax'] = 21;
$SeqWaterArray = array(58, 21);
$waterHot = $SeqWaterArray[0];
$waterCold = $SeqWaterArray[1];
$status = 0;
if ($waterHot < $row_WaterTemp['HotMin'] || $waterHot > $row_WaterTemp['HotMax']) {
$status = 1;
}
if ($waterCold > $row_WaterTemp['ColdMax']) {
$status = 1;
}
You can combine the if statements of course. I separated them because of readability.
Note that I removed all quotes from the numbers. Quotes are for strings, not for numbers.
You can use break statement in this case when the flag is set to 1. As per your specification the Cold water should be less than 21, I have modified the code.
<?php
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$row_WaterTemp['ColdMax'] = "21";
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$key = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
break;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val >= $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
break;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
echo $Status;
?>
This way it would be easier to break the loop in case if the temperature fails to fall within the range in either case.
https://eval.in/636912

Best way to check 3 variable values equals to zero inside if condition - PHP

I am checking 3 variables are equals to zero inside if condition , currently i am doing some thing like this
if($diff_colour_code==0 && $diff_upholstery_code==0 && $big_diff==0 )
is there any better way to do this
I am thinking a way like
if($diff_colour_code==$diff_upholstery_code==$big_diff==0 )
Please help , Thanks in advance .
This should work for you:
You can give the function as many arguments as you need!
<?php
$diff_colour_code = 0;
$big_diff = 0;
$diff_upholstery_code = 0;
function zeroCheck() {
foreach(func_get_args() as $arg)
if($arg == 0)
continue;
else
return false;
return true;
}
if (zeroCheck($diff_colour_code, $big_diff, $diff_upholstery_code))
echo "all are 0!";
?>
you can use ! as :
if(!$diff_colour_code && !$diff_upholstery_code && !$big_diff )
You could do something like this:
$var1 = 0;
$var2 = 0;
$var3 = 0;
$array = compact("var1", "var2", "var3");
$countValues = array_count_values($array);
if($countValues[0] == count($array)){
echo "yes";
}else{
echo "no";
}
or this
if(($var1 == 0 && $var1 == $var2 && $var2 == $var3)){
echo "yes";
}else{
echo "no";
}

PHP: Sort array according to another array of different length

I have two arrays of different length:
$paths_table = array("TS-0007_a.jpg", "TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0041_a.JPG", "TS-0041_b.JPG");
$order_table = array("TS-0040","TS-0007","TS-0041");
and I want to sort the first one using the second so that the output will be the array
$final_table = array("TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0007_a.jpg", TS-0041_a.JPG", "TS-0041_b.JPG")
Assuming that I'm going to use
strpos($paths_table[$i], $order_table[$j]);
to check if the string of $order_table is included in any of the $paths_table.
How can I accomplish this?
Preprocess the array so that each item contains an index of its prefix (that is, turn 'TS-0007_a.jpg' into [1,'TS-0007_a.jpg']):
foreach($paths_table as &$v) {
foreach($order_table as $n => $o)
if(strpos($v, $o) === 0) {
$v = [$n, $v];
break;
}
}
sort the array:
sort($paths_table);
and remove indexes:
foreach($paths_table as &$v)
$v = $v[1];
The following piece of code can off course be optimized in several ways, but for the sake of clarity I didnt.
$paths_table = array("TS-0007_a.jpg", "TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0041_a.JPG", "TS-0041_b.JPG");
$order_table = array("TS-0040","TS-0007","TS-0041");
$sorter = new PrefixSorter($order_table);
$output = usort($paths_table, array($sorter, 'sort'));
var_dump($paths_table);
class PrefixSorter {
private $prefixes;
function __construct($prefixes) {
$this->prefixes = $prefixes;
}
function sort($path1, $path2) {
$prefix1 = -1;
$prefix2 = -1;
foreach($this->prefixes as $index=>$prefix) {
if (substr($path1, 0, strlen($prefix)) == $prefix) $prefix1 = $index;
if (substr($path2, 0, strlen($prefix)) == $prefix) $prefix2 = $index;
}
if (($prefix1 == -1 && $prefix2 == -1) || $prefix1 == $prefix2) {
return 0;
}
else if ($prefix1 == -1 || $prefix1 > $prefix2) {
return 1;
}
else if ($prefix2 == -1 || $prefix1 < $prefix2) {
return -1;
}
}
}
I made a few assumptions:
You want to sort on the prefixes given in order_table
Prefixes not given are put at the back unordered.
You can off course change the code to match on string containment instead of prefixing

Categories