giorgio79
giorgio79

Reputation: 4199

php string variable containing as input for array function

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);

Upvotes: 0

Views: 470

Answers (3)

Michael Robinson
Michael Robinson

Reputation: 29498

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.

Upvotes: 2

Erik B
Erik B

Reputation: 42584

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?

Upvotes: 0

dwich
dwich

Reputation: 1723

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.

Upvotes: 2

Related Questions