Professional Documents
Culture Documents
Chapter 2 Function
Chapter 2 Function
Functions
• PHP Built-in Functions
• PHP has over 1000 built-in functions that can be called
directly, from within a script, to perform a specific task.
• function myMessage()
• { echo "Hello world!";
• }
Call a Function
• <?php
• function familyName($fname, $year) {
• echo "$fname Born in $year <br>";
• }
• familyName(“abc","1975");
• familyName(“pqr","1978");
• familyName(“mno","1983");
• ?>
• </body>
• </html>
PHP Default Argument Value
• The following example shows how to use a default
parameter. If we call the function setHeight() without
arguments it takes the default value as argument:
• <?php
• function setHeight($minheight = 50) {
• echo "The height is : $minheight <br>";
• }
• setHeight(350);
• setHeight();
• setHeight(135);
• setHeight(80);
• ?>
PHP Functions - Returning values
• To let a function return a value, use the return statement:
• <html>
• <body>
• <?php
• function sum($x, $y) {
• $z = $x + $y;
• return $z;
• }
• echo "5 + 10 = " . sum(5,10) . "<br>";
• echo "7 + 13 = " . sum(7,13) . "<br>";
• echo "2 + 4 = " . sum(2,4);
• ?>
• </body>
Variable Function
• PHP supports the concept of variable functions.
• This means that if a variable name has
parentheses appended to it, PHP will look for a
function with the same name as whatever the
variable evaluates to, and will attempt to execute
it.
• Variable functions won't work with language
constructs such
as echo, print, unset(), isset(), empty(), include,
require
Variable Function
• <?php <?php
• function hello() function add($x, $y)
• { {
• echo "Hello World"; echo $x+$y;
• } }
• $var="Hello"; $var="add";
• $var(); $var(10,20);
• ?> ?>
Anonymous functions
• Anonymous function is a function without any
user defined name.
• Most common use of anonymous function to
create an inline callback function.
• Syntax
• $var=function ($arg1, $arg2) { return $val; };
Anonymous functions
• There is no function name between the function
keyword and the opening parenthesis.
• There is a semicolon after the function definition
because anonymous function definitions are expressions
• Function is assigned to a variable, and called later using
the variable’s name.
• When passed to another function that can then call it
later, it is known as a callback.
• Return it from within an outer function so that it can
access the outer function’s variables. This is known as a
closure.
• <?php $var = function ($x) {
• return pow($x,3);
• };
• echo "cube of 3 = " . $var(3);
• ?>
• <?php
$greet = function($name) {
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
• Write anonymous function for multiplication
of two numbers
• Write anonymous function to find smallest of
two numbers
• <?php
• $multiply = function($a, $b) { return $a * $b; };
// Example usage
• $result = $multiply(5, 3);
• echo "Result: $result";
• ?>
• <?php
• // Example usage
• $number1 = 8;
• $number2 = 5;
• $smallest = $findSmallest($number1, $number2);
• echo "The smallest number is: $smallest"; // Output: The smallest number is: 5
• ?>
Math functions
• Basic Arithmetic Functions:
– abs($number): Returns the absolute value of a
number.
– ceil($number): Returns the next highest integer
value by rounding up.
– floor($number): Returns the next lowest integer
value by rounding down.
– round($number): Rounds a floating-point number
to the nearest integer.
• Exponential and Logarithmic Functions:
– exp($number): Returns the exponential value of a
number.
– log($number): Returns the natural logarithm of a
number.
– log10($number): Returns the base-10 logarithm of a
number.
– pow($base, $exponent): Returns the value of a base
raised to the power of an exponent.
– sqrt($number): Returns the square root of a number.
• Trigonometric Functions:
– sin($angle), cos($angle), tan($angle): Return the
sine, cosine, and tangent of an angle, respectively.
– asin($value), acos($value), atan($value): Return
the arcsine, arccosine, and arctangent of a value,
respectively.
– deg2rad($degrees), rad2deg($radians): Convert
degrees to radians and vice versa.
• Random Number Functions:
– rand($min, $max): Generate a random integer
between the specified minimum and maximum
values.
– mt_rand($min, $max): Generate a random integer
using the Mersenne Twister algorithm.
• Constants:
– M_PI: Represents the mathematical constant π
(pi).
• <?php
• $number = -7.5;
• echo "Absolute value: " . abs($number) . "\n";
• echo "Ceiling: " . ceil($number) . "\n";
• echo "Floor: " . floor($number) . "\n";
• echo "Round: " . round($number) . "\n";
• echo "Exponential: " . exp($number) . "\n";
• echo "Natural Logarithm: " . log(10) . "\n";
• echo "Base-10 Logarithm: " . log10(100) . "\n";
• echo "Power: " . pow(2, 3) . "\n";
• echo "Square Root: " . sqrt(25) . "\n";
• $angle = 45;
• echo "Sine: " . sin(deg2rad($angle)) . "\n";
• echo "Cosine: " . cos(deg2rad($angle)) . "\n";
• echo "Tangent: " . tan(deg2rad($angle)) . "\n";
• echo "Random Number: " . rand(1, 10) . "\n";
• echo "Random Number (Mersenne Twister): " . mt_rand(1, 10) . "\n";
• ?>
Basic graphics concepts
• It does not have built-in support for direct graphic manipulation
like some other languages such as JavaScript (for client-side
scripting) or Python (with libraries like Pillow).
• <?php
• $image = imagecreate(200, 100);//width=200 height=100
• //Background color of image
• $bgColor = imagecolorallocate($image, 255, 255, 255);
• $textColor = imagecolorallocate($image, 0, 0, 0);
• header("Content-type: image/png");
• imagepng($image);
• imagedestroy($image);
• ?>
• This script creates a simple image with a white background, black text, and outputs it as a PNG.
• <?php
• <?php
• // Original image path
• $originalImagePath = 'path/to/your/image.jpg';
• // Output the resized image to a file (you can also output to the browser or perform other actions)
• imagejpeg($resizedImage, 'path/to/your/resized_image.jpg');
• $pdf=new FPDF();: This line creates a new instance of the FPDF class, which
represents a PDF document.
• $pdf->SetFont('Arial','B',16);: This method sets the font for the text to be written. It
takes three parameters: font family (Arial in this case), font style (B for bold), and
font size (16).
• $pdf->Cell(40,10,'Hello World!');: This method adds a cell to the PDF document with
the text "Hello World!" inside. It takes four parameters: width of the cell (40 units),
height of the cell (10 units), text content ('Hello World!'), and other optional
parameters.