- A string is a sequence of characters enclosed in quotation marks, such as a name or a sentence. You can use letters, numbers or punctuation in a string. An array is a sequence of objects or values that maps each item to a key. You can include several different data types in an array, including strings, integers or Boolean values. In PHP, you get the value of a string variable by using the variable's name, but to use an array value, you have to call it using an index number.
- In PHP, you get the "fatal error: cannot use string offset as an array" error when you try to use a string variable as an array. For example, you can create a string called "$myvar" and assign a value to it. If you try to get the value by typing "$myvar[0]" (or some other index value), PHP will return the offset error because it cannot find the index value in memory, because -- technically -- the index does not exist.
- To prevent seeing this fatal PHP error, you can use the "array()" language construct to re-cast a string variable as an array. However, this will erase any value held by the string variable at the time. Alternatively, you can create another variable as an array and copy the value from the string to one of its indexes. This preserves the value in the string, but means you have to use a different variable name to access it, so if you use this variable elsewhere in the program, you will have to change the names in those locations.
- Some browsers will attempt to compensate for this error by trying to guess the value you want in your PHP program. For example, if you create a string called "$mystring" with "My string" as the value and then type "$mystring[3]" to get the fourth index from it, it might return just the letter "s," which is the fourth character in the string. While this avoids causing a fatal error, this might harm your program overall.
Arrays and Strings
Offset Error
Resolutions
Considerations
SHARE