In PHP, we usually use arrays to store or operate a bunch of related data. Sometimes, we need to convert a keyless array (that is, an array without a specified subscript) into a keyed array. This article will introduce how to convert a keyless array into a keyed array.
1. Why do you need to convert a keyless array into a keyed array
In PHP, an array can use numeric subscripts or string subscripts to access its elements. When we use numeric subscripts, PHP will assign a default subscript to the elements in the order they appear in the array. However, when we need to sort, search, or otherwise operate on an array, we need to use custom subscripts. At this time, if the array does not specify a subscript, it needs to be converted into a keyed array.
2. Use the array_combine() function to convert a keyless array into a keyed array
PHP provides an array_combine() function to combine two arrays into one array. The first parameter of the array_combine() function is the array used as the key name, and the second parameter is the array used as the key value. If the number of elements in the two arrays is not equal, the array_combine() function will return false.
When we want to convert a keyless array into a keyed array, we can first create a new key array, and then call the array_combine() function to combine it with the original array.
The following is a sample code to convert a keyless array into a keyed array:
$arr = [10, 20, 30, 40, 50]; // 无键数组 $keys = range(1, count($arr)); // 创建新的键名数组 $new_arr = array_combine($keys, $arr); // 将新的键名数组和原数组组合 print_r($new_arr); // 输出有键数组
Output result:
Array ( [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 )
3. Assign key names to array elements according to their type
Sometimes, we can also assign key names to array elements based on their type. For example, when the elements in the array are strings, you can use the string as the key name; when the elements are integers or floating point numbers, you can use the element value as the key name.
The following is a sample code to convert a keyless array into a keyed array:
$arr = ['apple', 'banana', 'orange']; // 无键数组 $new_arr = []; foreach ($arr as $key => $value) { if (is_string($value)) { // 如果元素是字符串 $new_arr[$value] = $value; // 使用字符串作为键名 } else { // 如果元素是数字 $new_arr[$value] = $value; // 使用元素值作为键名 } } print_r($new_arr); // 输出有键数组
Output result:
Array ( [apple] => apple [banana] => banana [orange] => orange )
4. Conclusion
Introduction to the above How to convert a keyless array to a keyed array. Using the array_combine() function and assigning keys based on element types allows us to easily handle keyless arrays and convert them into keyed arrays. In practical applications, you can choose a suitable method to process arrays according to the specific situation.
The above is the detailed content of php keyless array conversion. For more information, please follow other related articles on the PHP Chinese website!