mirza
mirza

Reputation: 5793

How to reach variable variables which has spaces?

I was curious about how to reach variable variables which contain spaces or special chars.

Is there a way to do ?

<?php
$first_day = "monday";
$$first_day = "first day of the week";
echo $monday." <br />";
$days = 'saturday sunday';
$$days = 'days of the weekend';
// how to echo $days of the weekend ???
print_r(get_defined_vars());

Upvotes: 2

Views: 89

Answers (1)

kittykittybangbang
kittykittybangbang

Reputation: 2400

According to the PHP docs:

A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

I.e., a variable name that contains spaces or special characters isn't a valid variable name, strictly speaking.

That being said, @mario's comment offers the workaround:

echo ${'saturday sunday'}; // echoes 'days of the weekend'

Upvotes: 2

Related Questions