0

I have an array where I would like to put spaces between the [] like :

$array[South Africa]=array();

But I can't... why this is not possible?

Buisson
  • 479
  • 1
  • 6
  • 23
  • 3
    Why do you need the spaces? Can you not use underscores or something? Here is a SO regarding spaces: http://stackoverflow.com/questions/2003036/php-using-spaces-in-associative-array-indices – Rasclatt Oct 13 '14 at 07:37
  • Do `$array['South Africa']` then? – SubjectCurio Oct 13 '14 at 07:40
  • I think better practice would be to do an underscore and if the key needs to be displayed for output in a formatted way (like a loop or something) just `str_replace("_"," ",$key);`. Something like that is probably better than a space. – Rasclatt Oct 13 '14 at 07:44
  • look as @Rasclatt pointed it out you can have space `$array['South Africa']=array();` it might be giving you error message as `south Africa` is not in `' '` single quete. Thanks – arif_suhail_123 Oct 13 '14 at 07:44
  • Yes I use str_replace("_"," ",$key); but I don't understand why spaces don't work . Thanks anyway :) – Buisson Oct 13 '14 at 07:57

1 Answers1

3

The correct way of doing this is:

$array['South Africa']  = array();

By not placing quotes around strings, PHP will first check if it is a constant, and if not assume you want to specify the string stated (and generate a warning).

This would work without a space (other than the warning and being bad practise) but with the space PHP thinks the string/constant has ended after 'South' and expects an ]. What you have specified will result in a syntax error:

 unexpected T_STRING, expecting ']'

I personally would avoid using spaces for names/keys anyway but the above explains the problem you are having if you must do this.

Mitch Satchwell
  • 4,770
  • 2
  • 24
  • 31