Advertisement
karlakmkj

php arrays

Sep 15th, 2021
924
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.85 KB | None | 0 0
  1. <?php
  2. namespace Codecademy;
  3.  
  4. // both ways can be used to declare an array
  5.   $with_function = array("PHP", "popcorn", "555.55");
  6.  
  7.   $with_short = ["PHP", "popcorn", "555.55"];
  8.  
  9.  
  10. $message = ["Oh hey", " You're doing great", " Keep up the good work!\n"];
  11.  
  12. $favorite_nums = [7, 201, 33, 88, 91];
  13.  
  14. // use implode() to print all elements in the array as one string together, with the first parameter as a $glue to join them together.
  15. echo implode("!", $message);
  16.  
  17. // use print_r() to print an array instead of using echo as it will output 'Array' only
  18. print_r($favorite_nums);
  19.  
  20. //to change elements in an array
  21. $change_me = [3, 6, 9];
  22.  
  23. // add elements to the end of an array using square brackets at the end of the array name before assignment operator!
  24. $change_me[] = "happy-go-lucky";  
  25. $change_me[] = 12;
  26. $change_me[1] = "kitten"; //change particular element using indexing
  27.  
  28. echo implode(",", $change_me);
  29.  
  30. // add and remove elements to end of array
  31. $stack = ["wild success", "failure", "struggle"];
  32.  
  33. array_push($stack, "blocker", "impediment"); // must indicate which array name in the first parameter, then what you want to add (in order to the end of the array)
  34.  
  35. array_pop($stack); // will remove the last element
  36.  
  37. // add and remove elements to BEGINNING of array
  38. $record_holders = [];
  39.  
  40. // will be added in this order index 0 - Tim, 1 - Maurice, 2 - Donovan etc..
  41. array_unshift($record_holders, "Tim Montgomery", "Maurice Greene", "Donovan Bailey", "Leroy Burrell", "Carl Lewis");
  42.  
  43. array_shift($record_holders); // will remove the first element
  44.  
  45. //Nested array
  46. $treasure_hunt = ["garbage", "cat", 99, ["soda can", 8, ":)", "sludge", ["stuff", "lint", ["GOLD!"], "cave", "bat", "scorpion"], "rock"], "glitter", "moonlight", 2.11];
  47.  
  48. print_r($treasure_hunt[3][4][2][0]); // count from garbage index 0 etc.. to get the element GOLD!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement