0

I'm trying to do simple addition on a variable within a string, using string parsing, like so:

$a = 2;
echo("I have {$a+1} eyes");

But PHP crashes when I do this.

I also tried {++$a}, but that outputs as I have {++2} eyes.

The PHP manual page for string parsing has no example covering arithmetic within a string.

Is this something that's possible?

UPDATE: I have to disagree with the duplicate question flag. That question is titled "How to increment a number inside foreach loop?". While the answers to that question do also answer mine, search engines will not find that question from a query like "How to increment in a PHP string", or "Arithmetic with PHP string interpolation". Even if the answers are the same, the questions are different.

murchu27
  • 527
  • 2
  • 6
  • 20
  • You can achieve this with concatenation. Are you explicitly looking to do it with variable interpolation like this? – El_Vanja Feb 22 '21 at 14:57
  • 2
    `printf("I have %d eyes", $a + 1);` – Alex Howansky Feb 22 '21 at 15:02
  • You could do `echo("I have " . ($a+1) . " eyes");` for example – The fourth bird Feb 22 '21 at 15:02
  • Yeah I was hoping for variable interpolation rather than concatenation, since I've read on here that interpolation is faster. Obviously if it's not an option I'll default to the concatenation/formatting options. – murchu27 Feb 22 '21 at 15:09
  • Don't optimize too early. Are you really having performance issues with the script that does this? If the answer is no, then don't worry about the speed of the operation. Go for code clarity. The crux is that interpolation allows variables, but not expressions. – El_Vanja Feb 22 '21 at 15:19
  • Sure thing. Do you want to put that in an answer and I'll accept it? – murchu27 Feb 22 '21 at 15:25
  • 1
    You say, *"search engines will not find that question"* ... but they may now find this question, which will act as a signpost to the other. That's how duplicates work. – Adrian Mole Jul 19 '22 at 03:19

1 Answers1

2

It's not possible through variable interpolation. It does not accept operations as arguments. What it does accept can be read in this question.

Alternatives:

  1. Store the result into a variable first. A bit of a redundant step, but is a way to do it with interpolation.
$a = 2;
$b = $a + 1;
echo "I have {$b} eyes";
  1. Use concatenation. Don't forget to wrap it in parentheses, because math operators don't have precedence over concatenation.
$a = 2;
echo "I have ".($a + 1)." eyes";
  1. Use a format printing function. Note that printf outputs the string, while sprintf returns it, so you'd have to explicitly output the latter.
$a = 2;
printf("I have %d eyes", $a + 1);
echo sprintf("I have %d eyes", $a + 1);
El_Vanja
  • 3,660
  • 4
  • 18
  • 21