In PHP, we usually use arrays (Array) to store a set of related data, such as saving a student's transcript or product information. Normally, we can use the array() function to create an array. But sometimes, we need to convert a scalar value (that is, a non-array value) into an array, and the array has only one element. In this case, we need to use the PHP method to force conversion to an array.
In PHP, we can use (array) or array() to force a scalar value to be converted into an array. This array has only one element. The key of this element defaults to 0, and the key value is the scalar value itself. The following is a sample code:
// 使用 (array) 进行强制转换 $value = "hello world"; $arr = (array)$value; print_r($arr); // 运行结果: Array ( [0] => hello world ) // 使用 array() 进行强制转换 $value = "hello world"; $arr = array($value); print_r($arr); // 运行结果: Array ( [0] => hello world )
As you can see, whether you use (array) for coercion or array() for coercion, the final result is an array with only one element. The key name is 0 and the key value is the original scalar value.
It should be noted that if the original scalar value itself is an array, the result of casting it into an array is different. Specifically, if you use (array) to cast, the original array will be retained; if you use array() to cast, the original array will be expanded into a new array.
The following is a sample code:
// 原来的标量值是一个数组 $value = array("hello", "world"); // 使用 (array) 进行强制转换 $arr = (array)$value; print_r($arr); //运行结果: Array ( [0] => hello [1] => world ) // 使用 array() 进行强制转换 $arr = array($value); print_r($arr); //运行结果: Array ( [0] => Array ( [0] => hello [1] => world ) )
As you can see, when using (array) for coercion, the original array is retained, and when using array() for coercion, the original The array is expanded into a new array.
In summary, PHP's method of coercion into an array can help us convert a scalar value into an array with only one element. The key name of this array is 0 and the key value is the original scalar value. Note that the results may be different if the original scalar value is itself an array.
The above is the detailed content of php forced conversion into array. For more information, please follow other related articles on the PHP Chinese website!