Home > Net >  Php string interpolation
Php string interpolation

Time:03-18

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"

CodePudding user response:

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.";

CodePudding user response:

you can try following line

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

CodePudding user response:

You can call a PHP var inside a string which is wrapped by double quoutes. But it is not possible with a function. 2 possible ways to do it:

$this->movies = ['lethal weapon 1','lethal weapon 9'];
$count = count($this->movies);
return "Your collection exists of $count movies.";

or

$this->movies = ['austin powers 1','austin powers 2'];
return "Your collection exists of " . count($this->movies) . " movies.";
  •  Tags:  
  • php
  • Related