views:

27

answers:

3

Why this does not work?

  $stringhaha ="     1 => General,
      2 => Business,
      3 => Entertainment,
      4 => Health,
      5 => Politics,
      6 => Sci/Tech,
      7 => Sports,
      8 => News";

$all_categories = array($stringhaha);

print_r($all_categories);

(will give an array with 1 item.)

While this works: If I include the variable content like this it will create properly an array with 8 items:

$all_categories = array(1 => General,
      2 => Business,
      3 => Entertainment,
      4 => Health,
      5 => Politics,
      6 => Sci/Tech,
      7 => Sports,
      8 => News);

print_r($all_categories);
+2  A: 

What is happening is exactly what you should expect: you've declared an array that contains one string.

It doesn't matter that your string looks like an array to us humans, PHP is merely PHP, and can't magically detect that you want it to parse an array from a string.

giorgio79, meet PHP Docs, your new best friend.

Michael Robinson
Ok thanks. Here is some more info for others coming after me:http://www.php.net/manual/en/language.types.array.php
+2  A: 

It's called language syntax. You cannot do whatever you want. You have to speak the language how it was designed.

This doesn't work either

message = hello

Why? Because it's not syntactically correct. Same applies for your example with array.

This is correct

$message = 'hello';

Every language has rules and you have to respect them. Good luck.

dwich
A: 

I think the correct syntax is:

$all_categories = array(1 => "General",
    2 => "Business",
    3 => "Entertainment",
    4 => "Health",
    5 => "Politics",
    6 => "Sci/Tech",
    7 => "Sports",
    8 => "News");

print_r($all_categories);

You do want an array of strings, right?

Erik B