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"
>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->barin"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->moviesas a string - because
$this->moviesis 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.";