Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php string interpolation

Tags:

php

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"

like image 256
Kai Meyers Avatar asked Aug 29 '26 15:08

Kai Meyers


1 Answers

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.";
like image 91
IMSoP Avatar answered Sep 01 '26 03:09

IMSoP