Does declaring an unnecessary variable in PHP consumes memory?

performance, php, variables

Solution

Don't make your code less readable just to save a few bytes. And this will not save you more, even if `$email` is a 100 MB string, because internally PHP uses the copy on write mechanism: The content of a variable is not copied unless you change it.

Example:

$a = str_repeat('x', 100000000); // Memory used ~ 100 MB
$b = $a;                         // Memory used ~ 100 MB
$b = $b . 'x';                   // Memory used ~ 200 MB

Problem

I usually do this in PHP for better readability but I don't know if it consumes memory or has any other issues? Let's say I have this code: ``` $user = getUser(); // getUser() will return an array ``` I could do: ``` $email = $user["email"]; sendEmail($email); ``` Without declaring the variable $email I could do: ``` sendEmail($user["email"]); ``` Which one is better? Consider that this is just a very simple example.

Original source