PHP: Fun with Arrays


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. $numbers = array( 1, 2, 3, 4, 5, 6 );
  3. print_r( $numbers );
  4. echo "<br /><br />";
  5.  
  6. //Remove the first element out of the array
  7. $a = array_shift( $numbers );
  8. echo "a: " . $a . "<br />";
  9. print_r( $numbers );
  10. echo "<br /><br />";
  11.  
  12. //Re-insert an element to the beginning of an array
  13. $b = array_unshift( $numbers, 'first' );
  14. echo "b: " . $b . "<br />";
  15. print_r( $numbers );
  16. echo "<br /><br />";
  17.  
  18. //Remove the last element from an array
  19. $c = array_pop( $numbers );
  20. echo "c: " . $c . "<br />";
  21. print_r( $numbers );
  22. echo "<br /><br />";
  23.  
  24. //Re-insert an element to the end of an array
  25. $d = array_push( $numbers, 'last' );
  26. echo "d: " . $d . "<br />";
  27. print_r( $numbers );
  28. echo "<br /><br />";
  29.  
  30. //How many items are in the array
  31. echo "Count: " . count( $numbers ) . "<br /><br />";
  32. //Maximum Value
  33. echo "Max Value: " . max( $numbers ) . "<br /><br />";
  34. //Minimum Value
  35. echo "Min Value: " . min( $numbers ) . "<br /><br />";
  36.  
  37. //Sort from lowest to higest
  38. echo "Sort: " . sort( $numbers );
  39. echo print_r($numbers) . "<br />";
  40.  
  41. //Sort from highest to lowest
  42. echo "Reverse Sort: " . rsort( $numbers );
  43. print_r($numbers) . "<br /><br />";
  44.  
  45. echo "<br /><br />";
  46. $implode = implode( " * ", $numbers );
  47. echo "Implode: " . $implode . "<br /><br />";
  48.  
  49.  
  50. //Take the String, find the delimiter, then turn it into an array
  51. echo "Explode: " . print_r( explode( " * ", $implode ) ) . "<br /><br />";
  52.  
  53.  
  54. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.