Simple PHP Stuff:Variable Evaluation

Simple PHP stuff : variable evaluation

Try using sprintf:

$sentence = '%s is a genius';
$subject = 'Einstein';
echo sprintf($sentence, $subject);

This will output Einstein is a genius

Simple PHP stuff : variable evaluation

Try using sprintf:

$sentence = '%s is a genius';
$subject = 'Einstein';
echo sprintf($sentence, $subject);

This will output Einstein is a genius

simple php Dollar $ evaluation in string questions

If the string is in double quotes, variables will be evaluated. If it's in single quotes, it's literal and you'll get exactly what you type.

$bar = 42;
'Foo $bar Baz' // Foo $bar Baz
"Foo $bar Baz" // Foo 42 Baz
'Foo ' . $bar . ' Baz' // Foo 42 Baz
'Foo ' . '$bar' . ' Baz' // Foo $bar Baz
"$bar " . $bar . " $bar" // 42 42 42

Here is the relevant manual section for a full explanation:

http://php.net/manual/en/language.types.string.php#language.types.string.parsing

To put actual quotes into the string, you'll need to alternate them or escape them.

'"$bar"'    // "$bar"
"'$bar'" // '42'
'\'$bar\'' // '$bar'
"\"$bar\"" // "42"
''$bar'' // syntax error, empty string '' + $bar + empty string ''

Also, what he said.

In PHP, is there a way to capture the output of a PHP file into a variable without using output buffering?

A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.

For example:

// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;

// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar


Related Topics



Leave a reply



Submit