Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Php string interpolation

How does string interpolation work in this scenario?
i’m not sure if i’m making a syntax error or not.

i’m trying to get the amount of items in this return

return "Your collection exists of {count($this->movies)} movies.";

when i try this it says:
"PHP Warning: Array to string conversion"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The string interpolation rules are described thoroughly in the PHP manual. Importantly, there are two main styles:

  • One with plain variables in the string, like "the $adjective apple", which also supports some expressions like $foo->bar in "the $foo->bar apple"
  • One with curly brackets, which supports more complex expressions, like {$foo->bar()}, but the expression must start with a $

When PHP sees your string:

  • it first sees {count(, but because the character after { isn’t $, it doesn’t mean anything special
  • it then sees the $this->movies, which is valid for the first syntax, so it tries to output $this->movies as a string
  • because $this->movies is an array, you get a Warning and the string "Array" is used

The result is that the string will always say "Your collection exists of {count(Array} movies.".


There is no interpolation syntax currently that supports function calls like count(), so you’ll have to use concatenation or an intermediate variable:

return "Your collection exists of " . count($this->movies) . " movies.";

or

$movieCount = count($this->movies);
return "Your collection exists of {$movieCount} movies.";

or

$movieCount = count($this->movies);
return "Your collection exists of $movieCount movies.";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading