Advertisement
FredrikPlays

Simple Array Example PHP

Jun 4th, 2020
1,403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.48 KB | None | 0 0
  1. <?php
  2. // Using array() to construct an array:
  3. $prime_numbers = array(2, 3, 5, 7, 11, 13, 17);  
  4.  
  5. // Using short array syntax:
  6. $animals = ["dog", "cat", "turtle", "cow"];  
  7.  
  8. // Printing with print_r():
  9. print_r($prime_numbers);
  10.  
  11. echo "\n\n";
  12.  
  13. // Printing with echo and implode()
  14. echo implode(", ", $animals);
  15.  
  16. // Adding an element with square brackets:
  17. $prime_numbers[] = 19;
  18.  
  19. // Accessing an array element:
  20. $favorite_animal = $animals[0];
  21. echo "\nMy favorite animal: " . $favorite_animal;
  22.  
  23. // Reassigning an element:
  24. $animals[1] = "tiger";
  25.  
  26. // Using array_pop():
  27. echo "\nBefore pop: " . implode(", ", $animals);
  28. array_pop($animals);
  29. echo "\nAfter pop: " . implode(", ", $animals);
  30.  
  31. // Using array_push():
  32. echo "\nBefore push: " . implode(", ", $prime_numbers);
  33. array_push($prime_numbers, 23, 29, 31, 37, 41);
  34. echo "\nAfter push: " . implode(", ", $prime_numbers);
  35.  
  36. //Using array_shift():
  37. echo "\nBefore shift: " . implode(", ", $animals);
  38. array_shift($animals);
  39. echo "\nAfter shift: " . implode(", ", $animals);
  40.  
  41. //Using array_unshift():
  42. echo "\nBefore unshift: " . implode(", ", $animals);
  43. array_unshift($animals, "horse", "zebra", "lizard");
  44. echo "\nAfter unshift: " . implode(", ", $animals);
  45.  
  46. //Using chained operations with nested arrays:
  47. $treasure_hunt = ["garbage", "cat", 99, ["soda can", 8, ":)", "sludge", ["stuff", "lint", ["GOLD!"], "cave", "bat", "scorpion"], "rock"], "glitter", "moonlight", 2.11];
  48.  
  49. echo "\nWe found " . $treasure_hunt[3][4][2][0];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement