简体   繁体   中英

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

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM