Hello. I will be a multiple.

Array output method to the screen:

function ShowArray($array, $message) { printf($message); foreach($array as &$value) { if(isset($value)) printf("%d\t", $value); } unset($value); // разорвать ссылку на последний элемент printf("<br/>"); } 

Next, I try to output the existing $ array array (1,2,3,4,5) already sorted, but I get an exception:

 ShowArray(arsort($array), "ARsort Array: "); // параметры: 1. массив, 2. заголовок 

Warning: Invalid argument for foreach () in C: \ Users \ KRYSHTOP-PC \ PhpstormProjects \ ArraysKryshtopenko \ index.php on line 76

  • Help please, and if you know a better way to display an array on the screen - share) - Kryshtop

3 answers 3

The arsort function does not return a new array, but a true or false sort result. Everything works for you, just do this:

 arsort($array); ShowArray($array, "ARsort Array: "); 

    arsort looks like this:

     bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) 

    Works with an array by reference and:

    Returns TRUE on success, or FALSE on error.

    That is, here:

     arsort($array) 

    you have true or false .

    Therefore, not a array is passed to the function, but a number (true - 1 or false - 0).

    To sort you need to write a sort before passing to the function.

     arsort($array); ShowArray($array, "ARsort Array: "); 

      I assume that you have taken an example of such a code from here .
      1) Why do you need a reference to $ value there if you just output an array to the screen? In the example, links are used to change the elements in the array, and then, so that in a subsequent call, foreach $ value does not refer to the last element in the new loop.
      2) arsort returns a boolean value, so the array must be sorted before calling the method.

      Before calling the method, sort:

       arsort($array); 

      Then call the method:

       ShowArray($array, "ARsort Array: "); // параметры: 1. массив, 2. заголовок 

      Try to make the method so, in my opinion, it will suit more:

       function ShowArray($array, $message) { printf($message); foreach($array as $value) { if(isset($value)) //спорный момент, т.к. цикл бегает по существующим элементам. printf("%d\t", $value); } printf("<br/>"); }