
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Forcing PHP to Use strings for Array Keys
Following are the ways to force PHP to use strings for array Keys
- Using php array() function
- Using json_encode() function
Using php array() Function
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);
Using json_read() Function
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);
Conclusion
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.