Home > Article > Backend Development > How to convert variable to array in php
In PHP, you can use the compact() function to convert one or more variables into an array. This function can create an array containing variable names and their values. The syntax format is "compact(var1,var2.. .)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php converts variables into arrays
<?php header("Content-type:text/html;charset=utf-8"); //多个变量转数组 $name = 'php中文网'; $url = 'www.php.cn'; $info = compact('name', 'url'); //传递变量名 print_r($info); ?>
Output:
rray ( [name] => php中文网 [url] => www.php.cn )
Description:
compact() function creates an array containing variable names and their values.
Any string that does not have a corresponding variable name is ignored.
Syntax
compact(var1,var2...)
Parameters | Description |
---|---|
var1 | Required. Can be a string with a variable name, or an array of variables. |
var2,... | Optional. Can be a string with a variable name, or an array of variables. Multiple parameters are allowed. |
Return value: Returns an array with all variable names and their values.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert variable to array in php. For more information, please follow other related articles on the PHP Chinese website!