Advertisement
karlakmkj

PHP built-in functions

Sep 14th, 2021
1,030
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.03 KB | None | 0 0
  1. <?php
  2. namespace Codecademy;
  3.  
  4. //Built-in functions
  5.  
  6. //reverse string
  7. echo strrev(".pu ti peeK .taerg gniod er'uoY");
  8.  
  9. //to lower case
  10. echo strtolower("SOON, tHiS WILL Look NoRmAL.");
  11.  
  12. //repeat string for certain no. of times
  13. echo str_repeat("\nThere's no place like home.\n", 3);
  14.  
  15.  
  16. $essay_one = "I really enjoyed the book. I thought the characters were really interesting. The plot of the novel was really engaging. I really felt the characters' emotions. They were really well-written. I really wish the ending had been different though.";
  17.  
  18. $essay_two = "Obviously this is a really good book. You obviously would not have made us read it if it wasn't. I felt like the ending was too obvious though. It was so obvious who did it right away. I think the thing with the light was obviously a metaphor for life. It would have been better if the characters were less obvious about their secrets.";  
  19.  
  20. // count the no. of times the substring in 2nd parameter appears in the string (1st parameter)
  21. echo substr_count($essay_one, "really");
  22.  
  23. echo substr_count($essay_two, "obvious"); //this includes "obviously" because the function is not concerned with which characters come before or after the string
  24.  
  25. // using absolute value function
  26. function calculateDistance($first, $second){
  27.   return abs($first - $second);
  28. }
  29.  
  30. //using round function
  31. function calculateTip($meal){
  32.   return round($meal*1.18);
  33. }
  34.  
  35. echo calculateDistance(-1,99);
  36. echo calculateTip(100);
  37.  
  38. // Random numbers generator
  39. echo getrandmax();  //to get the largest possible random integer
  40. echo "\n";
  41. echo rand();        // get number between 0 and the max above
  42. echo "\n";
  43. echo rand(1,52);    // get number within the range (1 and 52 inclusive)
  44.  
  45. // using str_pad() to understand PHP documentation
  46. $a = 29;
  47. $b = "You did it!";
  48. $c = STR_PAD_BOTH;
  49. $d = "*~*";
  50.  
  51. echo str_pad($b, $a, $d, $c);
  52.  
  53. // using other built-in functions
  54. function convertToShout($say){
  55.   return strtoupper($say) . "!";
  56. }
  57.  
  58. function tipGenerously($meal){
  59.   return ceil($meal*1.2);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement