Suppose you have a simple php array with named keys and integer values that works as expected across many php processes on a site.
for example:
$myArray = array();
$myArray['red'] = 5;
$myArray['blue'] = 3;
$myArray['car'] = 0;
$myArray['apple'] = 10;
However you pass the array to a simple function which causes php to throw a fatal error when trying to access any member of the array.
for example:
function myFunction($input,$myArray)
{
$count = $myArray['red'] + $myArray['car'];
}
The error produced is:
Fatal error: Uncaught TypeError: Cannot access offset of type string on string in /myFile.php:XX Stack trace: #0 /myFile2.php(XXX): myFunction() #1 {main} thrown in /myFile.php on line XX
The array will print inside the primary function and inside myFunction
with print_r($myArray)
and each print_r returns the expected result.
for example:
Array ( [red] => 5 [blue] => 3 [car] => 0 [apple] => 10 )
What is causing this problem?
The most similar post found in research is this post.
I have conducted tests before calling myFunction and inside myFunction to understand the array behaviour.
ie. inside mainFunction
print_r($myArray);
echo '<p> before:' . $myArray['red'];
myFunction($input,$myArray);
returns:
before: 5
Array ( [red] => 5 [blue] => 3 [car] => 0 [apple] => 10 )
ie. inside myFunction
print_r($myArray);
echo '<p> inside:' . $myArray['red'];
returns:
Fatal error: Uncaught TypeError: Cannot access offset of type string on string in /myFile.php:XX Stack trace: #0 /myFile2.php(XXX): myFunction() #1 {main} thrown in /myFile.php on line XX
Note:
the line echo '<p> inside:' . $myArray['red'];
causes the error to throw.
2
Answers
The problem is due to the machine being under provisioned; the code is fine.
Array String :-
This will throw an error because $str is a string, not an array.
This will also work because we are using the
is_array()
function to check if $var is an array.Snippet :-
$arr = ["John", "text"];
echo $arr[0];