1

I am trying to insert code in a php string dynamically. A simplified example would be:

echo "two plus three equals {2+3}"; //the code in the brackets would evaluate to 5

I know this can be done easily beforehand with:

$var = 2+3;
echo "two plus three equals $var";

But is it possible without the extra variable step or using eval?

Robbie
  • 700
  • 2
  • 6
  • 18
  • You might try sprintf `echo sprintf("two plus three equals %d", 2+3);` – The fourth bird Jan 19 '19 at 10:59
  • Is it possible? Sure, but you would need to write your own parser, unless @Thefourthbird's answer is satisfactory. – M. Eriksson Jan 19 '19 at 10:59
  • It is possible you need to use concatenate those number – Antu Jan 19 '19 at 11:01
  • 3
    A helper variable `$e="htmlentities";` would allow inline function expressions `echo "two plus three is {$e(2+3)}";`. – mario Jan 19 '19 at 11:08
  • "Code" can mean a lot of things. Are you just referring to simple arithmetic expressions or you want to be able to do anything? `echo 'User with ID {$db->prepare("INSERT INTO user (username) VALUES (?)")->exec(["jimmy"])->getInsertId()} has been created successfully.'` – Álvaro González Jan 19 '19 at 13:15

0 Answers0