2

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());
chris85
  • 23,846
  • 7
  • 34
  • 51
mirza
  • 5,685
  • 10
  • 43
  • 73
  • 8
    You could also use `${'variable name that you should not have in the first place'}` for accessing it. – mario Sep 01 '15 at 19:28
  • 1
    Yes, I'm 100% sure there is a much better way. – AbraCadaver Sep 01 '15 at 19:30
  • @mario could you please add your comment as an answer. it works. thanks and about your sarcasm it was just curiosity not that i needed to use it in a project. – mirza Sep 01 '15 at 19:34
  • 1
    don't worry @motto, this sarcasm is a relatively well known pun and not intended directly to you. Even though it really is funny... – Félix Adriyel Gagnon-Grenier Sep 01 '15 at 19:35
  • 1
    possible duplicate of [Can you have variables with spaces in PHP?](http://stackoverflow.com/q/29792444) (however that's just the literal answer). I'm pretty sure that's not what you're actually looking for. It looks like you actually would want to access the values the other way round. (Anyway, use an array. Less headaches, really.) – mario Sep 01 '15 at 19:35
  • In your particular case, `echo ${'saturday sunday'};`. In general: `print_r(array_filter(array_keys(get_defined_vars()), function ($v) { return ! preg_match('/^[a-z_][a-z0-9_]*$/i', $v); }));` – bishop Sep 01 '15 at 19:39
  • Most uses of variable variables can be done better using an associative array. – Barmar Sep 01 '15 at 19:43

1 Answers1

2

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'
kittykittybangbang
  • 2,380
  • 4
  • 16
  • 27