Advertisement
karlakmkj

Associative Arrays, By value, By reference

Sep 15th, 2021
4,923
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | None | 0 0
  1. <?php
  2. namespace Codecademy;
  3.  
  4. // create Associative Arrays in key-value pairs
  5. $php_array = array("language" => "PHP", "creator" => "Rasmus Lerdorf", "year_created" => 1995, "filename_extensions" => [".php", ".phtml", ".php3", ".php4", ".php5", ".php7", ".phps", ".php-s", ".pht", ".phar"]);
  6.  
  7. $giraffe_foods = ["dip"=>"guacamole", "chips"=>"corn", "entree"=>"grilled chicken"];
  8.  
  9. $impala_foods = ["dessert"=>"cookies", "vegetable"=>"asparagus", "side"=>"mashed potatoes"];
  10.  
  11. $rat_foods = ["dip"=>"mashed earth worms", "entree"=>"trash pizza", "dessert"=>"sugar cubes", "drink"=>"lemon water"];
  12.  
  13. $potluck = $giraffe_foods + $impala_foods;
  14. print_r($potluck);
  15. $potluck += $rat_foods; // $$rat_foods has duplicated keys with other arrays, so only unique keys will be added
  16. print_r($potluck);
  17.  
  18.  
  19. $doge_meme = ["top_text" => "Such Python", "bottom_text" => "Very language. Wow.", "img" => "very-cute-dog.jpg", "description" => "An adorable doge looks confused."];
  20.  
  21. $bad_meme = ["top_text" => "i don't know", "bottom_text" => "i can't think of anything", "img" => "very-fat-cat.jpg", "description" => "A very fat cat looks happy."];
  22.  
  23. // Assign by Value
  24. function createMeme($meme){
  25.   $meme ["top_text"] = "Much PHP";
  26.   $meme ["bottom_text"] = "Very programming. Wow.";
  27.   return $meme;  //Remember to return the array
  28. }
  29.  
  30. $php_doge = createMeme($doge_meme);  
  31. print_r($php_doge); // the array value changes
  32. print_r($doge_meme); // this array value remains the same - does not affect its original
  33.  
  34. // Assign by Reference - using & on the variable array
  35. function fixMeme(&$meme){
  36.   $meme ["top_text"] = "Apples & Pears";
  37.   $meme ["bottom_text"] = "Sweet fruits";
  38.   return $meme;
  39. }
  40.  
  41. $newMeme= fixMeme($bad_meme);
  42. print_r($newMeme);
  43. print_r($bad_meme);  // both the arrays have their values changes and they are the same
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement