Using php extract function with numeric indexes

时间:2018-09-18 19:50:09

标签: php arrays

I want to convert array values into variables using extract function. As extract function uses array keys as variable names and values as variable values. I have an array with numeric keys as shown:

$my_array = array(0 =>"Cat", 1=>"Dog", 2=>"Horse");
extract($my_array);

How i would use numeric keys here as variable names to access values? Or extract() just deal with string keys?

1 个答案:

答案 0 :(得分:2)

As per the manual,

You must use an associative array; a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

You can add a prefix to your extract() function. This would, in the example below, add the var_ prefix to each instance. You can supply whatever valid variable-prefix as the third argument - the created variables would reflect that parameter in the extract() function.

$my_array = array(0 =>"Cat", 1=>"Dog", 2=>"Horse");
extract($my_array, EXTR_PREFIX_ALL, "var");

The results can now be found in $var_0 through $var_2.