Php if template syntax error

Php – syntax error, unexpected ‘if’ (T_IF)

I think I’ve been staring at this for too long that now I’m failing to identify the problem.

Can someone kindly point out where this is going wrong?

Parse error: syntax error, unexpected 'if' (T_IF) in /Applications/MAMP/htdocs/mipbi/includes/classes/html.php on line 11 
public static function textbox($name, $maxlength='') < return "."' >"; > 

The error is generated at the if statement line.

Best Solution

You cannot use if statements in such a way. Use the ternary operator for that purpose or have your variable pre-made before the concatenation.

public static function textbox($name, $maxlength='')< return ""; > 
public static function textbox($name, $maxlength='') < if( !isset($_POST[$name] ) < $myname = $name; >else < $myname = ''; >return ""; > 
Php – Reference — What does this symbol mean in PHP
Example Name Effect --------------------------------------------------------------------- ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one. 

These can go before or after the variable.

If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.

Читайте также:  Java sun open source

In the case above ++$i is used, since it is faster. $i++ would have the same results.

Pre-increment is a little bit faster because it really increments the variable and after that ‘returns’ the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second’s.

However, you must use $apples— , since first, you want to display the current number of apples, and then you want to subtract one from it.

You can also increment letters in PHP:

Once z is reached aa is next, and so on.

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

Stack Overflow Posts:

Javascript – PHP parse/syntax errors; and how to solve them

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can’t guess your coding intentions.

Most important tips

There are a few basic precautions you can always take:

Expected: semicolon

  • Use proper code indentation, or adopt any lofty coding style. Readability prevents irregularities.
  • Use an IDE or editor for PHP with syntax highlighting. Which also help with parentheses/bracket balancing.
  • Read the language reference and examples in the manual. Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected T_STRING, expecting ‘ ; ‘ in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn’t process finally. This isn’t necessarily the cause of the syntax mistake, however.

It’s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.
    • For runaway strings and misplaced operators, this is usually where you find the culprit.
    • Read the line left to right and imagine what each symbol does.
    • In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )
    • If < code blocks >are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.
    • Strings and variables and constants should all have different colors.
    • Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context.
    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing » or ‘ string marker.
    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it’s not ++ , — , or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.
    1. The code you can easily identify as correct,
    2. The parts you’re unsure about,
    3. And the lines which the parser complains about.

    Partitioning up long code blocks really helps to locate the origin of syntax errors.

    • If you can’t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.
    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.
    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)
    • When you can’t resolve the syntax issue, try to rewrite the commented out sections from scratch.
    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn’t aid readability in all cases. Prefer plain if statements while unversed.
    • PHP’s alternative syntax ( if: / elseif: / endif; ) is common for templates, but arguably less easy to follow than normal < code >blocks.
    • Missing semicolons ; for terminating statements/lines.
    • Mismatched string quotes for » or ‘ and unescaped quotes within.
    • Forgotten operators, in particular for the string . concatenation.
    • Unbalanced ( parentheses ) . Count them in the reported line. Are there an equal number of them?
    • If you make one issue go away, but other crops up in some code below, you’re mostly on the right path.
    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)
    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.
    • Try grep —color -P -n «\[\x80-\xFF\]» file.php as the first measure to find non-ASCII symbols.
    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.
    • PHP just honors \n newlines, not \r carriage returns.
    • Which is occasionally an issue for MacOS users (even on OS X for misconfigured editors).
    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*. */ comments do seldom disturb the parser when linebreaks get ignored.
    • You are looking at the wrong file!
    • Or your code contained invisible stray Unicode (see above). You can easily find out: Just copy your code back from the web form into your text editor.
    • php -v for the command line interpreter

    Those aren’t necessarily the same. In particular when working with frameworks, you will them to match up.

    If all else fails, you can always google your error message. Syntax symbols aren’t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

    • PHP Debugging Basics by David Sklar
    • Fixing PHP Errors by Jason McCreary
    • PHP Errors – 10 Common Mistakes by Mario Lurig
    • Common PHP Errors and Solutions
    • How to Troubleshoot and Fix your WordPress Website
    • A Guide To PHP Error Messages For Designers — Smashing Magazine

    White screen of death

    If your website is just blank, then typically a syntax error is the cause. Enable their display with:

    In your php.ini generally, or via .htaccess for mod_php, or even .user.ini with FastCGI setups.

    Enabling it within the broken script is too late because PHP can’t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php :

    Then invoke the failing code by accessing this wrapper script.

    It also helps to enable PHP’s error_log and look into your webserver’s error.log when a script crashes with HTTP 500 responses.

    Источник

    php if<> elseif<> else<> syntax error [duplicate]

    else doesn’t take a condition. Also, single = is assignment; if you want to compare two values for equality, use == or === .

    3 Answers 3

     $userrole = $row['type']; if ($userrole == "admin") < $_SESSION['name'] = $row['name']; header("Location: ../index.php"); >elseif ($userrole == "encoder") < $_SESSION['name'] = $row['name']; header("Location: ../mencode.php"); >elseif ($userrole == "verifier") < $_SESSION['name'] = $row['name']; header("Location: ../mverify.php"); >elseif ($userrole == "approver") < $_SESSION['name'] = $row['name']; header("Location: ../mapproved.php"); >

    You made the fundamental error of all new PHP developers:

    • if($a=$b) is an assignment statement. It sets $b to whatever is on the right.
    • if($a==$b) is a comparison statement. It compares two values without changing anything.

    Change your statements to ($userrole==’…’) .

    $userrole = $row['type']; if ($userrole == "admin") < $_SESSION['name'] = $row['name']; header("Location: ../index.php"); >elseif ($userrole == "encoder") < $_SESSION['name'] = $row['name']; header("Location: ../mencode.php"); >elseif ($userrole == "verifier") < $_SESSION['name'] = $row['name']; header("Location: ../mverify.php"); >else < $_SESSION['name'] = $row['name']; header("Location: ../mapproved.php"); >

    Your if statements have to be comparison operators == and not assignment operators = .

    Also else is a catch all, so you don’t provide it with comparison values like you would with if or else if. I am a c++ programmer, but I’ve done a little PHP.

    Источник

    If statement inside php content, containing html code

    I have the above code, and I would like to know, if i can add an if statement inside style of 2nd td , so if ($result->name == «») . Is there any way that this can happen ? Notice that if name exists the above code will print the name, if not it will print an empty td . Thanks in advance!

    sure you can. Just break the concatenation, add an if that conditionally concatenates ‘display:none;’ and then concatenate the rest of the table

    Yes — you could a) use a ternary operator b) assign the class to a variable beforehand and include that in the echo c) break the $content var into bits and concatenate it with .= d) break it into bits with PHP template style syntax . have I missed any?

    if I break the concatenation, should then use a variable inside if statement including display: none and add it to next .= ?

    3 Answers 3

    Here’s a few ways you can do it:

       name>   "; 

    2: Assign the CSS to a variable and interpolate it

    name ? " display: none;" : ""; $content = " 
    name>
    ";

    3: Break the $content variable assignment into bits so you can use an if() condition

       name>   "; 

    4: Use PHP’s template style syntax

    This is my preferred option if you’re working in a template (a .phtml file for example).

    5: . or mix it up a bit (template style with a ternary echo)

     
    name; ?>

    Ultimately it comes down to which you find most readable and are most comfortable with.

    Источник

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

    I want to make the text red if username == user_id but it gives me a syntax error, unexpected ‘if’ (T_IF). my code:

    5 Answers 5

    It should be something like this

    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("> - "); > 

    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.

    Источник

Оцените статью