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>';
}
Related
I don't know how to write the if-condition inside the Href.The href is written in the PHP tags. and it gives me an error that Parse error: syntax error, unexpected 'if' (T_IF) in D:\Xampp\htdocs\Portal\admin\pages\ajax\EditDeleteAssignment.php on line 84
This is my code...
<?php $data .= '<tfooter>
<td colspan="2" class="text-center">
<ul class="pagination">
<li><a class="btn btn-primary" style="color:white;" href="?pageno=1" >First</a></li>
<li class="<?php if($pageno <= 1){ echo "disabled" } ">
<a class="btn btn-primary" style="color:white;" href="'.if($pageno <= 1){ echo "#"; } else { echo "?pageno=".($pageno - 1); }.'">Prev</a>
</table>';
echo $data;
?>
Try using a Ternary If
($pageno <= 1) ? "#" : "?pageno=" . ($pageno - 1) .
You're not necessarily writing this in an href, you're writing it in a string. PHP doesn't care what that HTML is, as far as it's concerned it's just a string. Simplified to:
$data .= '...' . if($pageno <= 1){ echo "#"; } else { echo "?pageno=".($pageno - 1); }. '...';
The syntax problem here is that you have multiple code lines, even multiple code blocks, on a single line of code. Fortunately, for simple conditional statemens which result in just a result to output, there's the ternary conditional operator. Something like this:
$data .= '...' . ($pageno <= 1 ? "#" : ("?pageno=" . ($pageno - 1))) . '...';
Notice the components thereing:
$pageno <= 1 // <-- the condition being checked
? // <-- the start of the operator, what's before it is the condition
"#" // <-- the result if true
: // <-- the second part of the operator, basically the "else"
("?pageno=" . ($pageno - 1)) // <-- the result if false
Note also the various parentheses used. Combining multiple concatenation operators throughout this conditional expression could easily confuse the parser or the programmer. Better to be explicit about the order of operations here.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I have a simple "if" code what works. In "array" it works but gets error "Undefined offset:". What is wrong?
code what works:
if (file_exists(glob($root . '/*/E0622.pdf')[0])) {
echo str_replace($root . '/', '', glob($root . '/*/E0622.pdf')[0]) ;
} else {
echo 'x.pdf - no-no-no!' ;}
but in array gets " Parse error: syntax error, unexpected 'if' (T_IF) in ":
'E0622' => 'E0622' . if (file_exists(glob($root . '/*/E0622.pdf')[0])) {
echo str_replace($root . '/', '', glob($root . '/*/E0622.pdf')[0])
} else {
echo 'x.pdf - no-no-no!' } ,
What will be wrong?
Tnx!
The if statement itself cannot be used the way you are trying to do.
However, a short-hand if-else statement exists. It is introduced for cases like yours.
It looks like this: conditional-expression ? value-when-true : value-when-false. This is an expression, so you can insert it everywhere you would insert any other expression.
$var = 7;
echo ($var == 7 ? "Var is seven" : "Var is not seven");
// Those parentheses are optional, but I added them for clarity.
It echoes "Var is seven".
This works:
'E0622' => 'E0622' . (file_exists(glob($root . '/*/E0622.pdf')[0]) ? str_replace($root . '/', '', glob($root . '/*/E0622.pdf')[0]) : 'x.pdf - no-no-no!'),
PS: While you can nest as many short-hand if-else statements as you want, things may start to get really messy:
$a = 1 == 1 ? 2 == 2 ? 3 == 4 ? 9 : 8 == 8 ? 1 : 2 : 7 : 6;
The if construct in PHP is not an expression, and cannot be used in concatenation.
You need to change your structure to setting a variable to the thing you want to concatenate first and then adding that variable to the string.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
The variable $n is readed from a form:
<?php
$nume=$_POST['n']
for($i=1;$i<=n;$i++)
{
for($j=1;$j<=n;$j++)
{
if($i==$j) $a[$i][$j]=0;
else $a[$i][$j]=$i;
echo $a[$i][$j]." ";
}
echo $a[$i][$j];
}
?>
Parse error: syntax error, unexpected 'for' (T_FOR) in C:\wamp\www\php
test 11F\test.php on line 3
What's the error, the problem?
It is my first project in php.
<?php
$n = 20;
for($i=1;$i<=$n;$i++)
{
for($j=1;$j<=$n;$j++)
{
if($i==$j)
$a[$i][$j]=0;
else
$a[$i][$j]=$i;
echo $a[$i][$j]." ";
}
}
?>
I fixed these issues,
n should be - $n
You are trying access value of $a[$i][$j] form outside the second loop - Then $j value equal to $n+1 - but you can get only 1 to $n
Outside the two loops print the array this way then you can see what are the accessible keys
echo "<pre>";
print_r($a);
echo "</pre>";
there is no semicolon after $_POST['n']. check below updated code
<?php
$nume=$_POST['n'];
for($i=1;$i<=$nume;$i++)
{
for($j=1;$j<=$nume;$j++)
{
if($i==$j) $a[$i][$j]=0;
else $a[$i][$j]=$i;
echo $a[$i][$j]." ";
}
echo $a[$i][$j];
}
?>
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';
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.