I use this code multiple times in my script. Is there a way to shorten this code? Thank you in advance.
if ($aUurverschil < 0){$avroegerkleur = "red";}
if ($aUurverschil > 0){$avroegerkleur = "green";}
if ($aUurverschil == 0){$avroegerkleur = "#48f442";}
if ($bUurverschil < 0){$bvroegerkleur = "red";}
if ($bUurverschil > 0){$bvroegerkleur = "green";}
if ($bUurverschil == 0){$bvroegerkleur = "#48f442";}
etc etc.
I use them in a div:
<div style="display:inline;color:<? echo $avroegerkleur;?>;">
You can abstract this logic:
if ($bUurverschil < 0){$bvroegerkleur = "red";}
if ($bUurverschil > 0){$bvroegerkleur = "green";}
if ($bUurverschil == 0){$bvroegerkleur = "#48f442";}
into a function, for example:
function getColor($uurverschil) {
return ($uurverschil < 0 ? "red" :
($uurverschil > 0 ? "green" :
("#48f442")));
}
Then anywhere you want to use that logic, just invoke that function with the value you're examining:
<div style="display:inline;color:<? echo getColor($aUurverschil); ?>;">
Related
If I'm trying to display a table (which I've accomplished with a while loop) but also display a count underneath it. Do I add another while loop? Or a seperate for loop? How would I do that? I need to count the number of performances (Ive got that working) but it wont tally the number of performances in Asheville. How do I target that variable by itself?
> <?php print ("<h1>Upcoming Performances in 2015</h1>"); print
> ("<table border =\"1\">"); print("<tr><th align =
> \"left\">Date</th><th align = \"left\">Venue</th><th align =
> \"left\">City</th><th align = \"right\">Ticket Price</th></tr>");
>
> $count = 0; $ashevilleCount = 0; $eventFile =
> fopen("performances.txt", "r"); $schedule = fgets($eventFile);
>
>
> while(!feof($eventFile)) { list($date, $venue, $city, $ticketPrice) = explode(":", $schedule);
> print("<tr><td>$date</td>"); print("<td>$venue</td>"); print("<td>$city</td>"); print("<td>$ticketPrice</td>");
> $schedule = fgets($eventFile);
> }
>
> for($count = 1; $count <= 5; $count = $count + 1) { $total = fgets($eventFile); $count = $count + $total;
> }
> if ($city == Asheville)
> $ashevilleCount = $ashevilleCount + $count;
>
>
>
>
>
> fclose($eventFile);
> print ("</table>");
>
> print ( "<p class=\"alert\">Lower cost venues are marked with
> *</p>"); print ("<p>NUMBER OF PERFORMANCES: $count</p>"); print ("<p>NUMBER OF PERFORMANCES IN ASHEVILLE: $ashevilleCount</p>");
>
>
>
>
> ?>
You need to take a look at your if statements.
if($condition === true){
//executes if $condition is true
} elseif($condition === 1) {
//executes if $condition is 1
} elseif($condition === 2 || $condition === 3){
//executes if $condition is 2 OR condition is 3
} elseif($condition === 4 && $otherCondition !== "foo"){
//executes if $condition is 4 AND $otherCondition is NOT "foo"
} else {
//executes if no other statements are true
}
This piece of code:
elseif
($charType == human or dwarf and $goldSpent <= 10)
$supplyTokens = $_POST['supplyTokens'] + 10;
Needs to look like:
} elseif( ( $charType=="human" || $charType=="dwarf" ) && $goldSpent <= 10) {
$supplyTokens = $_POST['supplyTokens'] + 10;
}
Remember:
|| = "or"
&& = "and"
test != "test" - make sure your strings are enclosed in quotation marks
See:
http://php.net/manual/en/control-structures.if.php
http://php.net/manual/en/control-structures.elseif.php
http://php.net/manual/en/language.operators.comparison.php
Here's your code cleaned up. What was done:
Changed all the print() commands to concatenated echos.
Fixed the conditionals
You don't need to check for $goldSpent <= 10 in your elseifs as you have already checked that by not being in $goldSpent > 10
I personally prefer || and && as opposed to or and and
Added curly brackets {}
Thing to consider:
What would happen if any of those $_POST values are empty??
<?php
$charName = $_POST['charName'];
$charType = $_POST['charType'];
$healthTokens = $_POST['healthTokens'];
$expTokens = $_POST['expTokens'];
$supplyTokens = $_POST['supplyTokens'];
$goldSpent = $healthTokens / 10 + $expTokens / 2 + $supplyTokens / 25;
if ($goldSpent > 10) {
echo "<h1>HEY THERE, $charName!</h1>" .
"<p>YOU SPENT MORE GOLD THAN YOU HAVE!</p>" .
"<p>GO BACK AND TRY THAT AGAIN - YOU HAVE 10 GOLD PIECES..</p>";
} elseif ($charType == 'elf') {
$healthTokens = $_POST['healthTokens'] + 5;
} elseif ($charType == 'wizard') {
$expTokens = $_POST['expTokens'] + 2;
} elseif ($charType == 'human' || $charType == 'dwarf') {
$supplyTokens = $_POST['supplyTokens'] + 10;
}
$totalGold = 10;
$goldLeft = $totalGold - $goldSpent;
echo "<h1>You have created $charName the $charType!</h1>" .
"<p>$charName has <strong>$healthTokens</strong> health tokens," .
"<strong>$expTokens</strong> experience tokens, and" .
"<strong>$supplyTokens</strong> supply tokens.</p>" .
"<p>You received some bonus tokens! :)</p>" .
"<p>$charName has spent <strong>$goldSpent</strong> gold pieces, " .
"and has <strong>$goldLeft</strong> gold pieces left.</p>";
I have the following code that suppose to change the background color after I enter the RGB color codes and click submit.
I don't know for what reason I get the "Undefined variable" and have a black background color before I click the submit button
< ?php
error_reporting(E_ALL);
ini_set('display_errors',true);
$form = "< form method='post' action=$_SERVER[PHP_SELF] >\n
R: < input type='text' name='r' >
G: < input type='text' name='g' >
B: < input type='text' name='b' >
< input type='submit' name='buton' value='go' >\n";
< /form >
$hexa = array();
$culoareHexa = array();
function &decimal2hexa($valoare) {
$valoriHexa = array('0'=>'0', '1'=>'1', '2'=>'2', '3'=>'3', '4'=>'4', '5'=>'5', '6'=>'6', '7'=>'7', '8'=>'8', '9'=>'9', '10'=>'A', '11'=>'B', '12'=>'C', '13'=>'D', '14'=>'E', '15'=>'F' );
if ($valoare <= 15) {
$numarHexa[] = $valoare;
$numarHexa[] = 0;
} else {
while ($valoare >= 15) {
$catul = $valoare / 16;
settype($catul, 'int');
$restul = $valoare % 16;
$valoare = $catul;
$numarHexa[] = $restul;
}
$numarHexa[] = $catul;
}
krsort($numarHexa);
foreach ($numarHexa as $key => $value) {
if ($value > 9) {
$numarHexa[$key] = $valoriHexa[$value];
}
}
$numarHexa = array_values($numarHexa); //reindexez si pastrez valorile pe pozitia initiala
return $numarHexa;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo $form;
} else {
if (!isset($_POST['r']) || !is_numeric($_POST['r']) || ($_POST['r'] > 255) || ($_POST['r'] < 0) ||
!isset($_POST['g']) || !is_numeric($_POST['g']) || ($_POST['g'] > 255) || ($_POST['g'] < 0) ||
!isset($_POST['b']) || !is_numeric($_POST['b']) || ($_POST['b'] > 255) || ($_POST['b'] < 0)) {
echo "date invalide!";
echo $form;
} else {
$culoareHexaR =& decimal2hexa($_POST['r']);
$culoareHexaG =& decimal2hexa($_POST['g']);
$culoareHexaB =& decimal2hexa($_POST['b']);
var_dump($_POST);
var_dump($culoareHexaR);
var_dump($culoareHexaG);
var_dump($culoareHexaB);
$culoareHexa = array_merge($culoareHexaR, $culoareHexaG, $culoareHexaB);
var_dump($culoareHexa);
$culoareHexaString = "";
for ($i = 0; $i < count($culoareHexa); $i++) {
$culoareHexaString .= $culoareHexa[$i];
}
echo $culoareHexaString;
}
}
? >
< html >
< body bgcolor="< ?php echo $culoareHexaString ? >">
< /body >
< /html >
If I declare the $culoareHexaString outside the if statement, it works just fine but I do not understand why.
in the following example it is not necessary to declade the $c variable outside the if statement.
$a = 5;
$b = 6;
if ($a > $b) {
echo "this will not be print";
} else {
$c = $a+$b;
}
$c variable will have a value of: < ?php echo $c ? >
what I am missing?
thanks!
Here:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
...
} else {
// code not executed on GET/initial page view
}
You initialize $culoareHexaString in a block that is never executed, because the first view/non-submit is a GET request, and thuse the else condition is ignored.
Try initializing a default value outside that block, like:
$coloareHexaString = '#000000'; // default value?
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
...
} else {
// code not executed on GET/initial page view
}
As for your example, echoing $c would also be undefined if $a < $b, as it was never initialized.
<?php
$a = 7;
$b = 6;
if ($a > $b) {
echo "this will not be print";
} else {
$c = $a+$b;
}
echo $c; // this will be undefined.
?>
Because $culoareHexaString is not setted.
When you use if-else statement, actually there will be code blocks and at the run time according to the statement related block content is handling.
for detecting value setting, use isset() method.
Also you can set default color at the beginning like;
< ?php
error_reporting(E_ALL);
ini_set('display_errors',true);
$culoareHexaString = "#000000";
$form = "< form method='post' action=$_SERVER[PHP_SELF] >\n
R: < input type='text' name='r' >
G: < input type='text' name='g' >
B: < input type='text' name='b' >
< input type='submit' name='buton' value='go' >\n";
< /form >
$hexa = array();
$culoareHexa = array();
.....
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";
}
How can I format this code block so that every time this loop happens,
it moves each hyperlink element 20px from the left?
It's working at the moment but for the whole div not single items.
Example:
- LINK 1
-- LINK 2
--- LINK 3
Any help would be appreciated!
$linkArray = array();
$thisDir = '';
$baseDir = ($htmlRoot == '') ? '' : $htmlRoot;
for ($n=0; $n<count($dirArray); $n++) {
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:20px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
$results = (count($linkArray) > 0) ? implode($separator, $linkArray) : '';
Well hmmm. You are already counting your iterations with the $n variable. SO:
EG.
for ($n=0; $n<count($dirArray); $n++) {
$pxvar = $n * 20;
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:'.$pxvar.'px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
Note: the first iteration will have a padding of 0px. Not sure if thats how you want it?
I am trying to perform some calculations with a form but every time i try to work with checkboxes it goes wrong.
The checkboxes are beign set on value 1 in the form itselff and are being checked if there checked or not.
$verdieping = isset($_POST["verdieping"]) ? $_POST["verdieping"] : 0;
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
When i try to do calculations every works expect for the options with the checkboxes.
When both checkboxes (telefoon & netwerk) are selected the value should be 30.
If only one is selected the value should be 20.
But no mather what i have tried to write down it always give problem, and it always uses 20, never the value 30.
How do i solve this problem? Or suppose i am writing the syntax all wrong to lay conditions to a calculation? Any input appreciated.
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
$verdieping = $_SESSION["verdieping"];
$telefoon = $_SESSION["telefoon"];
$netwerk = $_SESSION["netwerk"];
if ($oppervlakte <= 10)
$tarief = 100;
if ($oppervlakte > 10 && $oppervlakte <= 20)
$tarief = 90;
if ($oppervlakte > 20)
$tarief = 80;
if($verdieping == 1)
{
$prijsVerdieping = $oppervlakte * 120;
}
else
{
$prijsVerdieping = 0;
}
if(($telefoon == 1) && ($netwerk == 1))
{
$prijsCom = 30; // never get this value, it always uses 20
}
if(($telefoon == 1) || ($netwerk == 1))
{
$prijsCom = 20;
}
$prijsOpp = $tarief * $oppervlakte; // works
$totalePrijs = $prijsOpp + $prijsVerdieping + $prijsCom; //prijsCom value is always wrong
Regards.
EDIT: full code below in 2 php files
<?php
if (!empty($_POST))
{
$standnaam = $_POST["standnaam"];
$oppervlakte = $_POST["oppervlakte"];
//value in the form van checkboxes op 1 zetten!
$verdieping = isset($_POST["verdieping"]) ? $_POST["verdieping"] : 0; //if checkbox checked value 1 anders 0
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
if (is_numeric($oppervlakte))
{
$_SESSION["standnaam"]=$standnaam;
$_SESSION["oppervlakte"]=$oppervlakte;
$_SESSION["verdieping"]=$verdieping;
$_SESSION["telefoon"]=$telefoon;
$_SESSION["netwerk"]=$netwerk;
header("Location:ExpoOverzicht.php"); //verzenden naar ExpoOverzicht.php
}
else
{
echo "<h1>Foute gegevens, Opnieuw invullen a.u.b</h1>";
}
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="form1">
<h1>Vul de gegevens in</h1>
<table>
<tr>
<td>Standnaam:</td>
<td><input type="text" name="standnaam" size="18"/></td>
</tr>
<tr>
<td>Oppervlakte (in m^2):</td>
<td><input type="text" name="oppervlakte" size="6"/></td>
</tr>
<tr>
<td>Verdieping:</td>
<td><input type="checkbox" name="verdieping" value="1"/></td>
<!--value op 1 zetten voor checkbox! indien checked is value 1 -->
</tr>
<tr>
<td>Telefoon:</td>
<td><input type="checkbox" name="telefoon" value="1"/></td>
</tr>
<tr>
<td>Netwerk:</td>
<td><input type="checkbox" name="netwerk" value="1"/></td>
</tr>
<tr>
<td><input type="submit" name="verzenden" value="Verzenden"/></td>
</tr>
</table>
2nd page with calculations:
<?php
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
$verdieping = $_SESSION["verdieping"];
$telefoon = $_SESSION["telefoon"];
$netwerk = $_SESSION["netwerk"];
if ($oppervlakte <= 10)
$tarief = 100;
if ($oppervlakte > 10 && $oppervlakte <= 20)
$tarief = 90;
if ($oppervlakte > 20)
$tarief = 80;
if($verdieping == 1)
{
$prijsVerdieping = $oppervlakte * 120;
}
else
{
$prijsVerdieping = 0;
}
if(($telefoon == 1) && ($netwerk == 1))
{
$prijsCom = 30;
}
if(($telefoon == 1) || ($netwerk == 1))
{
$prijsCom = 20;
}
$prijsOpp = $tarief * $oppervlakte; // werkt
$totalePrijs = $prijsOpp + $prijsVerdieping + $prijsCom;
echo "<table class=\"tableExpo\">";
echo "<th>Standnaam</th>";
echo "<th>Oppervlakte</th>";
echo "<th>Verdieping</th>";
echo "<th>Telefoon</th>";
echo "<th>Netwerk</th>";
echo "<th>Totale prijs</th>";
echo "<tr>";
echo "<td>$standnaam</td>";
echo "<td>$oppervlakte</td>";
echo "<td>$verdieping</td>";
echo "<td>$telefoon</td>";
echo "<td>$netwerk</td>";
echo "<td>$totalePrijs</td>";
echo "</tr>";
echo "</table>";
?>
Terug naar het formulier
</body>
</html>
One problem I've noticed are these lines,
if(($telefoon == 1) && ($netwerk == 1)) {
$prijsCom = 30; // will get set to 30.
}
if(($telefoon == 1) || ($netwerk == 1)) {
$prijsCom = 20; // will now be set to value of 20.
}
Here is why, if $telefoon and $netwerk are both 1, $prijsCom is set to the value of 30. It leaves that if block and goes down onto the next one, i.e.
if(($telefoon == 1) || ($netwerk == 1)) {
$prijsCom = 20;
}
It will evaluate to true since $telefoon == 1 evaluates to true and will override the value of $prijsCom to be 20.
Depending on how the code will be used, as a possible work-around, you could add the || condition first, so the value is set to 20 whether $telefoon or $netwerk is set to 1 and then check to see if they both are 1.
Update:
When looking at your code, I notice you are using $_SESSION variables, but you have not called session_start() at the beginning of the file,
<?php
session_start(); // <--you need to call this first
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
...
This may or may not be where your other problem lies, but whenever you use $_SESSION you need to call session_start first.
Call session_start(); after <?php.