PHP Warning: ksort() expects parameter 1 to be array, string given in


I have an array of following format:

$entries = array('A2' => 'E2', 'A1' => 'E1', 'A3' => 'E3');

when I use ksort($entries), I get the following warning:

PHP Warning: ksort() expects parameter 1 to be array, string given in

When I use the array in a foreach loop, I get the following warning:

PHP Warning:  Invalid argument supplied for foreach() in

I get the warnings but the code produces the expected result just fine. I even tested gettype($entries) and it returned “array”. Is there a way to get rid of these warnings? Is it something related to the server?

Thanks for any ideas.

have you tried doing it with a non-assosiative array? (not name=>value)

Would be interesting to see if you still get the warnings

Actually, I get the same warnings for arrays in the following format:

$list = array('D1', 'D2', 'D3', 'D4');

As said, the code generates the expected results, just logs these warnings in the error_log file.

Perhaps try re-installing PHP. Could be a corrupted file or something.

Not a server I have control of. I will keep your suggestion in consideration though, thank you.

Does the warning message stack trace definitely point to a bit of code that you are looking at and appears to be correct?

Yes, the warnings point to specific lines in my code and the code appears to be correct, because I am getting the expected result. And as said, when I test the array variables with gettype() it returns “array”. Warnings claim they are “string”.

OK, that is very odd but just to completely rule out the possibility is something in your code, create a new empty php file, and copy and paste the following into it.

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";

That is from the php manual, so should work without errors.

  • If the warnings are still there then I can only imagine is it to do with the state of your installed php, Either a corrupted file or a strange setting.

  • Else if it works without errors, there it must be caused by something in your code or the specific php file.

1 Like

Thanks a lot! The code you gave worked fine with no warnings, but it helped me figure out the issue with my code. I was redefining the array variables at another place in the same array format which skipped from my attention. The reason it was providing expected result was because it was string but in the same array format. Thank you very much!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.