Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby addict looking for PHP subexpressions in strings

Context

  • PHP 5.3.x

Overview

After doing a code-review with an associate who uses both php and ruby routinely, a fun challenge came up on string interpolation in php compared to ruby.

Question

Assume color = "orange";

Ruby:

puts("My favorite color is #{color.downcase() + 'ish'} -- at least for now.");

PHP:

print("My favorite color is {strtolower( $color ) + 'ish'} -- at least for now.");

Challenge: can anyone specify a way to get the PHP version behave like Ruby?

Caveat

This challenge is intended as a fun exercise with the constraint of using only straight PHP. This is not intended for serious PHP projects. For serious PHP projects, the developer will want to consider addon libraries, such as TWIG.

like image 355
dreftymac Avatar asked Dec 05 '25 06:12

dreftymac


2 Answers

You're close, you can embed variables in strings, but not function calls.

I use printf() (and sprintf()) for that, which is a thin wrapper around the C function of the same name:

printf('My favorite color is %sish -- at least for now.', strtolower( $color ));

See that %s in there? That's the placeholder for the string data type that you're passing in as the 2nd argument.

sprintf() works the same way, but it returns the formatted string instead of print'ing it.

The only other options are:

A. Performing the function calls first and assigning the end-result to the variable:

$color = strtolower( $color );
print("My favorite color is {$color}ish -- at least for now.");

B. Using concatenation, which is a little ugly IMO:

print('My favorite color is ' . strtolower( $color ) . 'ish -- at least for now.');

You may have noticed my use of single quotes (aka ticks), and double quotes.

In PHP, literals inside double quotes are parsed for variables, as you see in "A" above.

Literals inside single quotes are not parsed. Because of this, they're faster. You should, as a rule, only use double-quotes around literals when there's a variable to be parsed.

like image 117
Shane H Avatar answered Dec 07 '25 20:12

Shane H


'My favorite color is ' . strtolower( $color ) . 'ish-- at least for now.'

I dont think PHP supports full expressions interpolated into strings. Been a while since I did any PHP though.

like image 35
Alex Wayne Avatar answered Dec 07 '25 20:12

Alex Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!