1 / 130

Unit-5

Unit-5. Functions. Math Functions. abs:-  Absolute value Returns the absolute value of number . If the argument number is of type float , the return type is also float, otherwise it is integer.

hdean
Download Presentation

Unit-5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit-5 Functions

  2. Math Functions • abs:-  Absolute value • Returns the absolute value of number. If the argument number is of type float , the return type is also float, otherwise it is integer. • <?php$abs = abs(-4.2); // $abs = 4.2; (double/float)$abs2 = abs(5);   // $abs2 = 5; (integer)$abs3 = abs(-5);  // $abs3 = 5; (integer)?>

  3. 2. Ceil:- Round fractions up • Returns the next highest integer value by rounding up value if necessary. • <?phpecho ceil(4.3);    // 5echo ceil(9.999);  // 10?>

  4. 3. Floor:-  Round fractions down • Returns the next lowest integer value by rounding down value if necessary • <?phpecho floor(4.3);   // 4echo floor(9.999); // 9?>

  5. 4. round:-  Rounds a float • float round ( float val [, int precision]) • Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default). • <?phpecho round(3.4);         // 3echo round(3.5);         // 4echo round(3.6);         // 4echo round(3.6, 0);      // 4echo round(1.95583, 2);  // 1.96echo round(1241757, -3); // 1242000echo round(5.055, 2);    // 5.06?>

  6. 5. fmod:- Returns the floating point remainder (modulo) of the division of the arguments - Returns the floating point remainder of dividing the dividend (x) by the divisor (y). -<?php$x = 6.5;$y = 1.5;$r = fmod($x, $y);// $r equals 0.5, ?>

  7. 6. min:- Find lowest value • min() returns the numerically lowest of the parameter values . • min ( number arg1, number arg2 [, number ...]) • <?phpecho min(2, 3, 1, 6, 7);  // 1echo min(array(2, 4, 5)); // 2echo min(0, 'hello');     // 0echo min('hello', -1);    // -1echo min('hello', 0);     // hello// With multiple arrays, min compares from left to right// so in our example: 2 == 2, but 4 < 5$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)// If both an array and non-array are given, the array// is never returned as it's considered the largest$val = min('string', array(2, 5, 7));   // string?>

  8. 7. Max:-Find highest value • max ( number arg1, number arg2 [, number ...]) • max() returns the numerically highest of the parameter values. • Example 1. <?phpecho max(1, 3, 5, 6, 7);  // 7echo max(array(2, 4, 5)); // 5echo max(0, 'hello');     // 0echo max('hello', 0);     // helloecho max(-1, 'hello');    // hello// With multiple arrays, max compares from left to right// so in our example: 2 == 2, but 4 < 5$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)// If both an array and non-array are given, the array// is always returned as it's seen as the largest$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)?>

  9. Note: PHP will evaluate a non-numeric string as 0, but still return the string if it's seen as the numerically highest value. • If multiple arguments evaluate to 0, max() will use the first one it sees (the leftmost value).

  10. 8. pow:- Exponential expression • pow ( number base, number exp) • Returns base raised to the power of exp. If possible, this function will return an integer. • <?phpvar_dump(pow(2, 8)); // int(256)echo pow(-1, 20); // 1echo pow(-1, 5.5); // error?>

  11. 9. sqrt:- Square root • sqrt ( float arg) • Returns the square root of arg. • <?php// Precision depends on your precision directiveecho sqrt(9); // 3echo sqrt(10); // 3.16227766 ...?>

  12. 10. rand:- Generate a random value • rand ( [int min, int max]) • <?phpecho rand() . "\n";echo rand() . "\n";echo rand(5, 15);?> • o\p:- 7771 • 22264 • 11

  13. Miscellaneous Functions • define:- Defines a named constant. • define ( string name, mixed value [, bool case_insensitive]) • The name of the constant is given by name; the value is given by value. • The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive;

  14. <?phpdefine("CONSTANT", "Hello world.");echo CONSTANT; // outputs "Hello world."echo Constant; // outputs "Constant"define("GREETING", "Hello you.", true);echo GREETING; // outputs "Hello you."echo Greeting; // outputs "Hello you."?>

  15. 2. Constant:- Returns the value of a constant • mixed constant ( string name) • constant() will return the value of the constant indicated by name. • constant() is useful if you need to retrieve the value of a constant, but do not know it's name. i.e. It is stored in a variable or returned by a function.

  16. <?phpdefine("MAXSIZE", 100);echo MAXSIZE;echo constant("MAXSIZE"); // same thing as the previous line?>

  17. 3. include:- The include() statement includes and evaluates the specified file. vars.php<?php$color = 'green';$fruit = 'apple';?>test.php<?phpecho "A $color $fruit"; // Ainclude 'vars.php';echo "A $color $fruit"; // A green apple?>

  18. E.X:- <?phpfunction foo(){    global $color;    include 'vars.php';    echo "A $color $fruit";}/* vars.php is in the scope of foo() so     ** $fruit is NOT available outside of this  ** scope.  $color is because we declared it ** as global.                               */foo();                    // A green appleecho "A $color $fruit";   // A green?>

  19. 4. require:- The require statement includes and evaluates the specified file. - When you include a file with the include command and PHP cannot find it you will see an error message like the following: E.X:- <?php include(“noFileExistsHere.php"); echo "Hello World!"; ?> o\p:- Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Warning: main(): Failed opening 'noFileExistsHere.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2Hello World!

  20. <?php require("noFileExistsHere.php"); echo "Hello World!"; ?> - o\p:- Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2Fatal error: main(): Failed opening required 'noFileExistsHere.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2

  21. 5. header:- Send a raw HTTP header • void header ( string string [, bool replace [, int http_response_code]]) • It is important to notice that header() must be called before any actual output is sent • <?php // The output above is before the header() call header('Location: http://localhost/T.Y.B.C.A/break1.php/'); echo "tanvi"; ?>

  22. 6.die:- The die() function prints a message and exits the current script. • This function is an alias of the exit() function. • <?php $x=1; if($x==0) { print "OK"; } else die("Unable to connect to $site"); ?>

  23. String Function • chr:-  Return a specific character • string chr ( int ascii) • Returns a one-character string containing the character specified by ascii. • <?php$str .= chr(65); /* add an escape character at the end of $str */echo $str; //The string ends in escape: A ?>

  24. 2. ord :-  Return ASCII value of character • int ord ( string string) • Returns the ASCII value of the first character of string. <?php $str = ord("The string ends in escape: "); echo $str;//84 ?>

  25. 3. strtolower:-  Make a string lowercase • string strtolower ( string str) • Returns string with all alphabetic characters converted to lowercase. • <?php$str = “XYZ";$str = strtolower($str);echo $str; // xyz ?>

  26. 4. strtoupper:- Make a string uppercase • string strtoupper ( string string) • Returns string with all alphabetic characters converted to uppercase. • <?php$str = “Xyz";$str = strtoupper($str);echo $str; // Prints XYZ?>

  27. 5. strlen:- Get string length • int strlen ( string str) • Returns the length of string. • <?php $str = 'abcdef';//6 echo strlen($str); $str=' abc de'; echo strlen($str); // 7 ?>

  28. 6. ltrim :-  Strip whitespace from the beginning of a string • string ltrim ( string str [, string charlist]) • <?php$text = “ These are a few words :) ...  ";$trimmed = ltrim($text);// $trimmed = These are a few words :)…?>

  29. 7. rtrim --  Strip whitespace from the end of a string. • string rtrim ( string str [, string charlist]) • <?php$text = "These are a few words :) ...  ";$trimmed = rtrim($text);// $trimmed = These are a few words :) ...?>

  30. 8. substr -- Return part of a string • string substr ( string string, int start [, int length]) • substr() returns the portion of string specified by the start and length parameters. • If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

  31. <?php$rest = substr("abcdef", 1);    // returns bcdef$rest = substr("abcdef", 1, 3); // returns bcd$rest = substr("abcdef", 0, 4); // returns abcd$rest = substr("abcdef", 0, 8); // returns abcdef ?> • If start is negative, the returned string will start at the start'th character from the end of string.

  32. <?php$rest = substr("abcdef", -1);    // returns f$rest = substr("abcdef", -2);    // returns ef$rest = substr("abcdef", -3, 1); // returns d?> • If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than start characters long, FALSE will be returned.

  33. If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned. • <?php$rest = substr("abcdef", 0, -1);  // returns abcde$rest = substr("abcdef", 2, -1);  // returns cde$rest = substr("abcdef", -3, -1); // returns de?>

  34. 9. strcmp:- Binary safe string comparison • int strcmp ( string str1, string str2) • Returns < 0 if str1 is less than str2; • Returns > 0 if str1 is greater than str2, and • Return 0 if they are equal. • Note:- that this comparison is case sensitive. • <?php echo strcmp("xy","xyz");//-1 ?>

  35. 10.strcasecmp:- case-insensitive string comparison • int strcasecmp ( string str1, string str2) • Returns < 0 if str1 is less than str2; • Returns > 0 if str1 is greater than str2, • Returns 0 if they are equal. • <?php$var1 = "Hello";$var2 = "hello";if (strcasecmp($var1, $var2) == 0) {    echo “$var1 is equal to $var2 in a case-insensitive string comparison”;}?>

  36. 11. strpos --  Find position of first occurrence of a string • int strpos ( string haystack, string needle [, int offset]) • Returns the numeric position of the first occurrence of needle in the haystack string. • If needle is not found, strpos() will return boolean FALSE. • <?php$newstring = 'abcdef abcdef';$pos = strpos($newstring, 'a', 1); // $pos = 7?>

  37. 12. strrpos --  Find position of last occurrence of a char in a string. • int strrpos ( string haystack, string needle [, int offset]) • Returns the numeric position of the last occurrence of needle in the haystack string • If needle is not found, returns FALSE.

  38. <?php $pos = strrpos("abcdefb", "b"); if ($pos == false) { echo "not found..."; } else echo $pos; ?> o/p:- 6

  39. 13. strstr:-Find first occurrence of a string • string strstr ( string haystack, string needle) • Returns part of haystack string from the first occurrence of needle to the end of haystack. • If needle is not found, returns FALSE. • If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

  40. Note: This function is case-sensitive. For case-insensitive searches, use stristr(). • Example 1. • <?php$email = 'user@example.com';$domain = strstr($email, '@');echo $domain; // prints @example.com?>

  41. 14. stristr:- string stristr ( string haystack, string needle) • Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner. • If needle is not found, returns FALSE. • If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

  42. <?php  $email = 'USER@EXAMPLE.com';  $domain = stristr($email, 'e');  echo $domain; // outputs ER@EXAMPLE.com?>

  43. 15. str_replace:- Replace all occurrences of the search string with the replacement string • mixed str_replace ( mixed search, mixed replace, mixed subject ) • This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

  44. <?php // Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); echo $newphrase = str_replace($healthy, $yummy, $phrase); ?>

  45. 16. strrev -- Reverse a string • string strrev ( string string) • Returns string, reversed. • <?phpecho strrev("Hello world!"); // outputs "!dlrow olleH"?>

  46. 17. echo -- Output one or more strings • void echo ( string arg1 [, string argn...]) • Outputs all parameters. • echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it. • In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses.

  47. <?phpecho "Hello World";echo "This spansmultiple lines. The newlines will be output as well";?>

  48. 18 print:- Output a string • int print ( string arg) • print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list. • <?phpprint("Hello World");print "print() also works without parentheses.";?>

  49. Array Function • count -- Count elements in a variable • int count ( mixed var [, int mode]) • Returns the number of elements in var, which is typically an array. • If var is not an array, 1 will be returned • If the optional mode parameter is set to COUNT_RECURSIVE , count() will recursively count the array.

  50. <?php$a[0] = 1;$a[1] = 3;$a[2] = 5;$result = count($a);// $result == 3$b[0]  = 7;$b[5]  = 9;$b[10] = 11;$result = count($b);// $result == 3;?>

More Related