Skip to content
Home » Web » PHP » How to Parse Variables in a String

How to Parse Variables in a String

Parse error: syntax error, unexpected ''

To use a plain-old variable to represent the element of array is a safe way in a double-quotes string. Here is a demonstration:

<?php
$username = $_POST['username'] = "Alex Howard";
echo "select * from users where username = '$username'";
?>

The output is:

select * from users where username = 'Alex Howard'

No error in the output, it's very safe in logic. But if there were hundreds of elements in the array, you may be sick of creating another hundreds of variables as representatives.

To reuse the array might be a cleaner way to do it. But you will need to care the syntax.

This does not work:

<?php
$_POST['username'] = "Alex Howard";
echo "select * from users where username = '$_POST['username']'";
?>

The output shows that is a syntax error:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in <file_path>

Solutions

There're several ways to solve the parse error.

Curly Syntax

Yes, it's a syntax error indeed, you must follow the official way to do it. The correct syntax is to add a pair of curly brackets to escape the element of array.

<?php
$_POST['username'] = "Alex Howard";
echo "select * from users where username = '{$_POST['username']}'";
?>

Concatenation

Or you can do it by concatenating it:

<?php
$_POST['username'] = "Alex Howard";
echo "select * from users where username = '" . $_POST['username'] . "'";
?>

The output is normal now:

select * from users where username = 'Alex Howard'

Without Single Quotations

Missing outer single quotes results another type of error in the following case, but it's not a PHP error this time, it's a SQL error due to forget to wrap the predicate in string:

<?php
...
$statement = $dbh -> prepare("select * from users where username = {$_POST['username']}");
$statement -> execute();
...
?>

You can see more complex string processing like heredoc and nowdoc in the official document: PHP: Strings - Manual.

The above string $statement will be parsed into an unacceptable SQL statement as below, because "username" is a character-typed column in essence, not a number, so it will need single quotes to indicate the value.

select * from users where username = Alex Howard

An exception will be thrown.

Leave a Reply

Your email address will not be published. Required fields are marked *