Home >Backend Development >PHP Tutorial >How can I force PHP to use strings for array keys?
To force PHP to use strings for array keys is quite easy, as in PHP array keys are automatically stored as integers if the array elements are numbers. If they are not numbers then it will cast to strings.
Following are the ways to force PHP to use strings for array Keys
If you use the array() function and keep the first key in quotes it will take other keys as a string does not matter if you are using numeric values. As we have shown in the given example.
<?php $array = array("first" => "Tutorialspoint", 2 => "Simply Easy Learning"); $new_array = array("first", "second"); $new_array = array_combine($new_array, $array); print_r($new_array);
By using the json_read() function you can return a string containing the JSON representation of the supplied value. After that, we can use json_decode(), which will return a value encoded in JSON in the appropriate PHP type.
<?php $array = array("first" => "Tutorialspoint", 2 => "Simply Easy Learning"); $json = json_encode($array); $new_array = json_decode($json, true); print_r($new_array);
Here we have shown two ways to force php to use strings for array keys. You can use any one approach to achieve what you are looking for.
The above is the detailed content of How can I force PHP to use strings for array keys?. For more information, please follow other related articles on the PHP Chinese website!