Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

Chapter 2

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.

• Besides the built-in PHP functions, it is possible to create


your own functions.
• A function is a block of statements that can be used
repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
Create a Function

• A user-defined function declaration starts with


the keyword function, followed by the name
of the function:

• function myMessage()
• { echo "Hello world!";
• }
Call a Function

• To call the function, just write its name


followed by parentheses ():
• Example
• function myMessage()
• { echo "Hello world!";
• }
• myMessage();
PHP Function Arguments

• Information can be passed to functions


through arguments. An argument is just like a
variable.
• Arguments are specified after the function
name, inside the parentheses. You can add as
many arguments as you want, just separate
them with a comma.
• <html>
• <body>
• <?php
• function familyName($fname) {
• echo "$fname CM6I.<br>";
• }
• familyName("abc");
• familyName("xyz");
• familyName("pqr");
• familyName("mno");
• familyName("Borge");
• ?>
• </body>
• </html>
• <html>
• <body>

• <?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

• // Anonymous function to find the smallest of two numbers


• $findSmallest = function($a, $b) {
• return ($a < $b) ? $a : $b;
• };

• // 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).

• However, PHP can be used in conjunction with other technologies


to handle graphics on the server-side or generate dynamic images.
Here are some concepts related to basic graphics handling in PHP:

• 1. Image Handling Libraries:


• - GD (Graphics Draw): GD is a library in PHP that allows dynamic
image creation and manipulation. It provides functions to create
and manipulate images in various formats. You can use it to draw
shapes, add text, resize images, and more.
• 2. **Generating Dynamic Images:**
• - With the GD library, you can create dynamic images on the fly. For example, you can create a
simple image with text using functions like `imagecreate()`, `imagestring()`, etc.

• <?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);

• //bool imagestring ( $ image , $ font , $ x , $ y , $ string , $ color )

• imagestring($image, 4, 10, 40, "Hello, PHP!", $textColor);

• 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

• // Create the size of image or blank image


• $image = imagecreate(500, 300);

• // Set the background color of image


• $background_color = imagecolorallocate($image, 0, 153, 0);

• // Set the text color of image


• $text_color = imagecolorallocate($image, 255, 255, 255);
• // Function to create image which contains string.
• imagestring($image, 5, 180, 100, "GeeksforGeeks", $text_color);
• imagestring($image, 3, 160, 120, "A computer science portal", $text_color);
• header("Content-Type: image/png");
• imagepng($image);
• imagedestroy($image);
• ?>
Scaling Image

• <?php
• // Original image path
• $originalImagePath = 'path/to/your/image.jpg';

• // Load the original image


• $originalImage = imagecreatefromjpeg($originalImagePath);

• // New width and height for the scaled image


• $newWidth = 300; // Set your desired width
• $newHeight = 200; // Set your desired height

• // Create an empty image with the new dimensions


• $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

• // Resize the original image to the new dimensions


• imagecopyresized($resizedImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($originalImage),
imagesy($originalImage));

• // 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');

• // Free up memory by destroying the images


• imagedestroy($originalImage);
• imagedestroy($resizedImage);
• ImageCopyResampled
• This function is used to resize an image to a
specified width and height while preserving the
original aspect ratio.
• It provides a higher quality result compared to
imagecopyresized as it uses interpolation to
resample the image.
• imagecopyresampled($destination_image,
$source_image, $dest_x, $dest_y, $src_x, $src_y,
$dest_width, $dest_height, $src_width,
$src_height);
Creation of pdf document
• To generate PDF files with PHP by using FPDF.
• It is a free PHP class that contains many
functions for creating and modifying PDFs.
• The FPDF class includes many features like page
formats, page headers, footers, automatic page
break, line break, image support, colors, links,
and many more.
• Approach:
• You need to download the FPDF class from the
FPDF website and include it in your PHP script.
• require('fpdf/fpdf.php');
• Instantiate and use the FPDF class according to
your need as shown
• $pdf=new FPDF();
• <?php
• require('fpdf/fpdf.php');
• // Instantiate and use the FPDF class
• $pdf = new FPDF();
• //Add a new page
• $pdf->AddPage();
• // Set the font for the text
• $pdf->SetFont('Arial', 'B', 18);
• // Prints a cell with given text
• $pdf->Cell(60,20,'Hello GeeksforGeeks!');
• // return the generated output
• $pdf->Output();
• ?>
• require('./fpdf.php');: This line includes the FPDF library file named "fpdf.php". This
library provides functions and classes to create PDF files.

• $pdf=new FPDF();: This line creates a new instance of the FPDF class, which
represents a PDF document.

• $pdf->AddPage();: This method adds a new page to the 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.

• $pdf->Output();: This method generates the output PDF. If no filename is provided, it


sends the PDF to the browser. You can also specify a filename to save the PDF to the
server instead of outputting it to the browser.

You might also like