user970638
user970638

Reputation: 129

PHP: Complicated String With Single and Double Quotes

I'm trying to pass GET variables inside the URL with a bit of html inside of my PHP but can't figure out the quotes situation. I need to embed two variables inside the URL. I have one in but don't know how to embed the other. Here is the string:

echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";

and here is what I need to go inside

&City=$City

Thanks for the help

Upvotes: 0

Views: 78

Answers (5)

Joris Ros
Joris Ros

Reputation: 379

Maybe is it better to use the sprintf function

$id = 100;
$previousId = $id - 1;
$City = 'Amsterdam';
$link = '<a href="?id=%1$s&City=%2$d" class="button">PREVIOUS</a>';

echo sprintf($link, $id, $City);

Upvotes: 1

worldofjr
worldofjr

Reputation: 3886

You do need (well, it's good practice anyway) to use &amp; for your ampersand. Otherwise it's fairly straight forward;

echo "<a href='?id=".($id-1)."&amp;City=$City' class='button'>PREVIOUS</a>";

This is because you are using double quotes, which means you can put variables directly into the string (there are some exceptions which you might need to put in curly brackets {}).

I suggest you get a text editor with syntax highlighting, such as jEdit (other editors are available).

Hope this helps.

Upvotes: 1

mercredo
mercredo

Reputation: 158

Use something like this:

echo "<a href='?id=".$id."&City=".$city."'>";

Upvotes: 1

GramThanos
GramThanos

Reputation: 3622

In php double quotes "" can eval variables inside them.

$test = "123;"
echo "0$test456"; // prints 0123456

In your case you better use single quote ''.

echo '<a href=\'?id=' . ($id-1) . '&City=' . $City . '\' class=\'button\'>PREVIOUS</a>';

or better

echo '<a href="?id=' . ($id-1) . '&City=' . $City . '" class="button">PREVIOUS</a>';

Upvotes: 1

CuriousMind
CuriousMind

Reputation: 3173

Its pretty simple,

echo "<a href='?id=".($id-1)."&city=" . $City . "' class='button'>PREVIOUS</a>";

Upvotes: 3

Related Questions