How to echo two pieces of information - php

I have this code:
if($tempPrice > 500)
{
echo $tempPrice*0.038;
}
else
{
echo 'NA';
}
What I want to do is put a '£' before the '$tempPrice*0.038' but not before the NA. So when it outputs it outputs '£123' with the tempprice and 'NA' if there isn't a tempprice.

Using the . sign you can echo multiple parts.
echo "£" . ($tempPrice*0.038);

You can just add it to the beginning of your echo statement:
echo '£' . ($tempPrice*0.038);
Learn more about string operators here: http://php.net/manual/en/language.operators.string.php

Just concatenate it in the first if statement. You can also use the single line notation, like so:
<?php
echo ($tempPrice > 500) ? '£' . ($tempPrice*0.038) : 'NA';

Related

PHP syntax error, unexpected 'if' (T_IF) [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I want to make the text red if username == user_id but it gives me a syntax error, unexpected 'if' (T_IF). my code:
foreach ($dag as $taak) {
echo '<li' if($_SESSION['user_id'] == $taak['username']){ echo 'style="color:red"';}'>'.$taak['taak_naam'].' - '.$taak['username'].'</li>';
}
anyone any idea?
It should be something like this
echo '<li';
if($_SESSION['user_id'] == $taak['username']){
echo ' style="color:red"';
}
echo '>'.$taak['taak_naam'] . ' - ' .$taak['username'] . '</li>';
Don't mix decisions (if ...) with output. Prepare everything before echoing:
foreach ($dag as $taak) {
// Don't add color by default
$style = '';
// Special color for special entries
if ($_SESSION['user_id'] == $taak['username']) {
$style = ' style="color: red;"';
}
// Make sure HTML special characters in $taak['username'] do not break the HTML
$username = htmlspecialchars($taak['username']);
// Display
echo("<li{$style}>{$taak['taak_naam']} - {$username}</li>");
}
By surrounding the string in double quotes ("), PHP recognizes variable names inside it and replaces them with their values.
The curly braces ({ and }) around the array values tell PHP the variable is $taak['taak_naam'], otherwise it finds only $taak and it outputs Array['taak_naam'] (which is not what we want).
If a value you use to create HTML content might contain characters that are special in HTML then you must encode those characters using their correct HTML definition. The PHP function htmlspecialchars() knows how to do it.
It encodes <, >, & and " (these are HTML breakers if they are not encoded properly). If you need to encode all the symbols that are defined in HTML as "character entities" you can use the PHP function htmlentities() instead.
you cannot use if between the strings
foreach ($dag as $taak) {
$style='';
if($_SESSION['user_id'] == $taak['username'])
$style='style="color:red"';
echo "<li {$style}> {$taak['taak_naam']} - {$taak['username']}</li>";
}
****OR****
foreach ($dag as $taak) { ?>
<li <?php if($_SESSION['user_id'] == $taak['username'])
echo 'style="color:red"'; ?> >
<?= $taak['taak_naam'].' - '.$taak['username']; ?>
</li>';
<?php
}
Forgot the semicolon.
foreach ($dag as $taak) {
echo '<li';
if($_SESSION['user_id'] == $taak['username']) {
echo ' style="color:red"';
}
echo '>'.$taak['taak_naam'].' - '.$taak['username'].'</li>';
}
You can use the short if syntax, the long syntax is not allowed in this context:
foreach ($dag as $taak) {
echo '<li' . (($_SESSION['user_id'] == $taak['username']) ? ' style="color:red"' : '') . '>' .$taak['taak_naam'] . ' - ' . $taak['username'].'</li>';
}

How to convert a string in a number PHP

I have a Foreach where I have two variables ($num1 and $num2) as string. I'd like to covert them as number (integer should be ok).
This is my code:
...
foreach ($titles as $match) {
list($num1, $num2) = explode(':', $results[$c++]->innertext); // <- explode
echo "<tr><td class='rtitle'>".
"<td class='last-cell'>".$match_dates[$c]->innertext . "</td> " .
//"<td class='first-cell tl'>".$match->innertext."</td> " .
" - ".$match->innertext." ".$num1.':'.$num2 . " " .
"<td class='odds'>".$best_bets[$b++]->attr['data-odd'] . ";" .
"".$odds[$b++]->attr['data-odd'] . ";" .
"".$odds[$b++]->attr['data-odd'] . "</td>" .
"</td></tr><br/>";
}
...
Thanks!
EDIT
Thanks for your answer. I am going to explain and maybe you could help me: I have a a problem with best_bets value, because it's not alway before odds variable, so I was thinking to use "if statement", where I can fix some rules: when $num1 is > $num2, I will show an echo order; when $num1 is = $num2 another echos order and. at least, $num1 is < $num2 another echos order. But to do this, I need to convert $num1 and $num2 to do it. I hope to be clear. Thank you for your helping
You could cast them to an int:
$num1 = (int) $num1;
Or use the intval function:
$num1 = intval($num1);
Hope this helps.

unexpected result in php output with larger strings

I am trying to create a binary/hexadecimal converter to convert a denary(base 10) number/value into binary and hexadecimal.
It works fine so far for binary until the input from the form is greater than 11 digits and over(string length), ruffly as it seems to variety. after 11 digits it starts adding " - " into the outcome. Im not sure were this is coming from as I don't have an " - " in the code.
I wasn't sure if this was something to do with large integers as I saw some other questions on that topic(not in php however it was java, so not sure if there is something simpler in php)
That said I was under the impression that form inputs were always strings.
To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric(). - from : http://www.php.net/manual/en/function.is-float.php
(haven't yet got to hexadecimal but needed to mention it as some of the following code contains parts for it.)
here is the php code (note: I do check user input just not added it yet)
$inpu = $_POST['number'];
$numinput = $_POST['number'];
if (is_numeric($numinput))
{
while ($numinput >= 1)
{
$binary .= $numinput % 2;
$numinput = $numinput / 2;
}
$mult = strlen($binary) % 4;
echo gettype($numinput) . "<br />";
echo gettype($binary) . "<br />";
echo gettype($mult) . "<br />";
echo $mult . "<br />";
while ($mult < 4)
{
$binary.= "0";
$mult++;
}
$revbinary = strrev($binary);
echo $inpu . " in binary = " . $revbinary ;
echo "<br /> <br />";
echo chunk_split($revbinary, 4);
echo "<br />" . gettype($revbinary) . "<br />";
echo gettype($inpu) . "<br />";
}
else
{
if (is_numeric($numinput))
{
echo "$numinput is over the max value of 255";
}
else
{
echo "your entry is not a vaild number <br />";
echo $numinput;
}
}
Im not looking for completed version of this code as you would ruin my fun, I am just wondering why there is a "-" being entered after 11 digits or so. It also did't add the symbol before I added :
$mult = strlen($binary) % 4;
echo $mult . "<br />";
while ($mult < 4)
{
$binary.= "0";
$mult++;
}
This was to split the binary into 4s ( 0011 1101 0010 0110 ).
Edit: wondered if this would be useful:
echo gettype($numinput); result double
echo gettype($binary); result string
echo gettype($mult); result integer
gettype($revbinary); result string
echo gettype($inpu); result string
still trying to work this out myself.
Any advice is much appreciated Thanks
I would suggest simply using decbin() and dechex(). Those are functions included in php, which do exactly what you're trying to accomplish.
You might want to check if it is a number first (like you are already doing).
Then cast it to an integer (through intval()) and then apply decbin() and dechex()
http://php.net/manual/de/function.decbin.php
http://www.php.net/manual/de/function.dechex.php
http://php.net/manual/de/function.intval.php

changing font makes + combine strings instead of adding values

Here is my code:
<?php
$num1 = 10;
$num2 = 15;
echo "<font color='red'>$num1 + $num2</font>" . "<br>";
?>
I expect it to equal "25", when I add a font color it equals "10 + 15". Why?
You cannot do math inside a string. Instead, close the string. perform your addition operation, and concatenate the result.
echo "<font color='red'>" . ($num1 + $num2) . "</font><br>";
As Orangepill wisely points out, this can be accomplished more efficiently like this:
echo "<font color='red'>",($num1 + $num2),"</font><br>";
change
echo "<font color='red'>$num1 + $num2</font>" . "<br>";
to
echo "<font color='red'>",($num1 + $num2),"</font><br>";
You need to concatenate your string otherwise math will not work
echo "<font color='red'>".($num1 + $num2)."</font>" . "<br>";

printf inside echo [duplicate]

This question already has answers here:
Why does echo combined with printf displays wrong output? [duplicate]
(3 answers)
How to concatenate strings with function calls while using echo?
(6 answers)
Closed 11 months ago.
How do you insert a printf comment inside of an echo? I have been trying to figure it out for the past hour and everything I try results in a different error.
Below is the last version of the code that I tried.
<?php
$i = 0;
do {
echo "<li><a class=\"th radius\" href=\"img/coolstuff/" . printf("%03d", $i); . ".jpg\"><img src=\"img/coolstuff/" . printf("%03d", $i); . ".jpg\"></a></li>";
$i++;
} while ($i < 282);
?>
Remove the ; before the ., otherwise you're terminating the statement.
Additionally, printf directly outputs the string, which will make it appear at the start of the outputted string. You want sprintf instead.
Use sprintf() instead. It returns the formatted string instead of outputting it.
Also, as #Kolink mentioned, remove the semicolons, so your echo would look like this:
echo "<li><a class=\"th radius\" href=\"img/coolstuff/" . sprintf("%03d", $i) . ".jpg\"><img src=\"img/coolstuff/" . sprintf("%03d", $i) . ".jpg\"></a></li>";
Do like this:
echo "<li><a class=\"th radius\" href=\"img/coolstuff/" , printf("%03d", $i);
Notice the comma , instead of dot ..
When using a comma with a echo statement, like above, each part is evaluated first. Atleast according to this accepted anwer.

Categories