PHP set array with variable

时间:2016-04-04 16:58:43

标签: php arrays

I want to make an array with a variable which has some array values. The problem is I am trying to add dynamic value in an array which has a fixed format. Here is my code:

$array_value="'id','name'";    
$aColumns = array( $array_value );

But it's not working. So array should be like(expected):

$aColumns = array( 'id','name' );

Thanks in advance.

2 个答案:

答案 0 :(得分:2)

You can use explode to convert your string to an array and str_replace for replacing the apostrophes.

$aColumns = explode(',', str_replace('\'', '', $array_value));

答案 1 :(得分:1)

it seems like, you are going wrong with the format and expected declarations.

$array_value holds the value, which means you have assigned a value to the variable, and this holds "'id','name'" value completely.

if you think you require an array using a string, than you go with use of explode() expects two parameters,

  1. a needle, here in your case it is ,

  2. the string to be exploded, in your case it is 'id','name'