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"
The string interpolation rules are described thoroughly in the PHP manual. Importantly, there are two main styles:
"the $adjective apple", which also supports some expressions like $foo->bar in "the $foo->bar apple"{$foo->bar()}, but the expression must start with a $When PHP sees your string:
{count(, but because the character after { isn't $, it doesn't mean anything special$this->movies, which is valid for the first syntax, so it tries to output $this->movies as a string$this->movies is an array, you get a Warning and the string "Array" is usedThe 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.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With