Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Codecademy;
- // both ways can be used to declare an array
- $with_function = array("PHP", "popcorn", "555.55");
- $with_short = ["PHP", "popcorn", "555.55"];
- $message = ["Oh hey", " You're doing great", " Keep up the good work!\n"];
- $favorite_nums = [7, 201, 33, 88, 91];
- // use implode() to print all elements in the array as one string together, with the first parameter as a $glue to join them together.
- echo implode("!", $message);
- // use print_r() to print an array instead of using echo as it will output 'Array' only
- print_r($favorite_nums);
- //to change elements in an array
- $change_me = [3, 6, 9];
- // add elements to the end of an array using square brackets at the end of the array name before assignment operator!
- $change_me[] = "happy-go-lucky";
- $change_me[] = 12;
- $change_me[1] = "kitten"; //change particular element using indexing
- echo implode(",", $change_me);
- // add and remove elements to end of array
- $stack = ["wild success", "failure", "struggle"];
- 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)
- array_pop($stack); // will remove the last element
- // add and remove elements to BEGINNING of array
- $record_holders = [];
- // will be added in this order index 0 - Tim, 1 - Maurice, 2 - Donovan etc..
- array_unshift($record_holders, "Tim Montgomery", "Maurice Greene", "Donovan Bailey", "Leroy Burrell", "Carl Lewis");
- array_shift($record_holders); // will remove the first element
- //Nested array
- $treasure_hunt = ["garbage", "cat", 99, ["soda can", 8, ":)", "sludge", ["stuff", "lint", ["GOLD!"], "cave", "bat", "scorpion"], "rock"], "glitter", "moonlight", 2.11];
- 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