Advertisement
Guest User

Quick PHP Quiz

a guest
Sep 25th, 2017
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. <?php
  2. function list_cmp($a, $b) {
  3. global $order;
  4.  
  5. foreach ($order as $key => $value) {
  6. if ($a == $value) {
  7. return 0;
  8. }
  9.  
  10. if ($b == $value) {
  11. return 1;
  12. }
  13. }
  14. }
  15.  
  16. $order[0] = 1;
  17. $order[1] = 3;
  18. $order[2] = 4;
  19. $order[3] = 2;
  20.  
  21. $array[0] = 2;
  22. $array[1] = 1;
  23. $array[2] = 3;
  24. $array[3] = 4;
  25. $array[4] = 2;
  26. $array[5] = 1;
  27. $array[6] = 2;
  28.  
  29. usort($array, "list_cmp");
  30. ?>
  31.  
  32. /*
  33. What is the logic / thinking / explanation of:
  34. 1) Comparing a value of $a to a value of the $order array and if they are the same doing nothing (return 0)
  35. 2) If $a is not equal to a value of the $order array, comparing $b to a value of the $order array, and if $b equals a value of the $order array, returning 1, which moves the (current) $b variable towards the end of the array (higher index)?
  36. The goal is to sort the $array based on the order of the $order array, but what is the explanation of achieving this with how this code is set up? I am not getting this yet…
  37. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement