0

I'm having hard time with quotation marks. I have this line of code;

echo "<a href='$bName'_read.php?bid='$bid'&id='$next_id[id]'>NEXT</a>";

with 3 variables, $bName,$bid, and $next_id[id].

There is something wrong with the quotations I've used. I also tried this;

echo "<a href='".$bName."_read.php?bid=".$bid."&id=".$next_id['id']."'">";

but it's still not working.

Can anyone explain how quoting works in this case please?

7
  • 1
    Looks like a proper job for sprintf instead Commented Dec 28, 2014 at 17:33
  • 1
    None of those variables need to be quoted inside that string, but $bname should be {} enclosed as href='{$bname}_read.php?... and the entire href string should be quoted Commented Dec 28, 2014 at 17:34
  • 2
    For readability and unambiguity, they will all benefit from {} As in echo "<a href='{$bName}_read.php?bid={$bid}&id={$next_id['id']}'>NEXT</a>"; Commented Dec 28, 2014 at 17:35
  • only the url needs quotes. you might want to literally write down an example output, if this is not immediately obvious to you... Commented Dec 28, 2014 at 17:36
  • 2
    @PeeHaa Meh - it's messy no matter which approach - interpolation, concatenation, sprintf, they're all ugly for a url. Commented Dec 28, 2014 at 17:38

1 Answer 1

4

You don't need to put single quotes around every PHP variable. It should make sense in HTML instead, for example;

echo "<a href='{$bName}_read.php?bid={$bid}&amp;id={$next_id['id']}'>NEXT</a>";

You need curly braces ({}) around object and array variables, but it is also useful for normal variables. Also, the array index should be in quotes as it is a string (not required for integer indexes).

Additionally, I changed the ampersand (&) to &amp; as & signifies the start of a special character code (just like &amp;), so although in this case it wouldn't be a problem it is best practice to put the HTML char code in, even in a URL.

Sign up to request clarification or add additional context in comments.

2 Comments

Inside the {} the array key [id] must be quoted or it will cause undefined constant id notices. {$next_id['id']}
Ah yes, well spotted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.