Blog

  • PHP String Functions Complete Reference

    PHP String Functions Complete Reference

    The predefined math functions in PHP are used to handle mathematical operations with integer and float types. These math functions are built into PHP and do not require any additional installation.

    Installation: These functions do not require any special installation. The complete list of PHP math functions is given below:

    Example: A program illustrating the decbin() function in PHP:

    <?php
    echo decbin(45);
    ?>

    Output:

    101101

    ImagickDraw::annotation()
    Description: Draws text at specified coordinates on the image.
    Example:

    $draw->annotation(50, 100, "Sample Text");
    // Output: (draws "Sample Text" at position (50, 100))

    ImagickDraw::arc()
    Description: Draws an arc between two points with a specified start and end angle.
    Example:

    $draw->arc(50, 50, 200, 200, 0, 90);
    // Output: (draws an arc from 0° to 90° within the bounding box (50, 50) to (200, 200))

    ImagickDraw::bezier()
    Description: Draws a bezier curve using specified control points.
    Example:

    $draw->bezier([[10, 10], [30, 90], [60, 30], [80, 80]]);
    // Output: (draws a bezier curve passing through the defined points)

    ImagickDraw::circle()
    Description: Draws a circle with a center point and a point on the radius.
    Example:

    echo chop("Hello World!  ");
    // Output: Hello World!

    ImagickDraw::getStrokeOpacity()
    Description: Returns the opacity of stroked outlines.
    Example:

    echo $draw->getStrokeOpacity();
    // Output: (returns the opacity level of the stroke)

    ImagickDraw::getStrokeWidth()
    Description: Returns the stroke width used for outlines.
    Example:

    echo $draw->getStrokeWidth();
    // Output: (returns stroke width value)

    ImagickDraw::line()
    Description: Draws a line between two points.
    Example:

    $draw->line(10, 10, 300, 300);
    // Output: (draws a line from (10, 10) to (300, 300))

    ImagickDraw::point()
    Description: Draws a point at specified coordinates.
    Example:

    $draw->point(150, 150);
    // Output: (draws a point at coordinate (150, 150))

    ImagickDraw::polygon()
    Description: Draws a polygon using an array of vertex points.
    Example:

    $draw->polygon([[10, 10], [100, 50], [50, 100]]);
    // Output: (draws a polygon with vertices at the specified points)

    ImagickDraw::polyline()
    Description: Draws a series of connected lines through specified points.
    Example:

    $draw->polyline([[10, 20], [30, 40], [50, 60], [70, 80]]);
    // Output: (draws connected lines through the defined points)

    ImagickDraw::rectangle()
    Description: Draws a rectangle defined by two opposite corners.
    Example:

    $draw->rectangle(10, 10, 200, 100);
    // Output: (draws a rectangle from (10, 10) to (200, 100))

    ImagickDraw::rotate()
    Description: Applies rotation to the coordinate space.
    Example:

    echo password_hash("mypassword", PASSWORD_DEFAULT);
    // Output: $2y$10$...

    ImagickDraw::roundRectangle()
    Description: Draws a rectangle with rounded corners.
    Example:

    $draw->roundRectangle(10, 20, 200, 150, 20, 20);
    // Output: (draws a rectangle with rounded corners of radius 20)

    ImagickDraw::scale()
    Description: Applies scaling to the horizontal and vertical directions.
    Example:

    $draw->scale(1.5, 1.2);
    // Output: (scales coordinate space by 1.5 horizontally and 1.2 vertically)

    ImagickDraw::setFillColor()
    Description: Sets the color used for filling shapes.
    Example:

    $draw->setFillColor('green');
    // Output: (sets fill color to green)

    ImagickDraw::setFillOpacity()
    Description: Sets the opacity level for the fill color.
    Example:

    $draw->setFillOpacity(0.5);
    // Output: (sets fill opacity to 50%)

    ImagickDraw::setFont()
    Description: Sets the font for text drawing.
    Example:

    $draw->setFont('Courier');
    // Output: (sets text font to Courier)

    ImagickDraw::setFontFamily()
    Description: Sets the font family to use for text.
    Example:

    $draw->setFontFamily('Arial');
    // Output: (sets font family to Arial)

    ImagickDraw::setFontSize()
    Description: Specifies the font size for text.
    Example:

    $draw->setFontSize(20);
    // Output: (sets text font size to 20 points)

    ImagickDraw::setFontStyle()
    Description: Sets the style for text, such as italic or normal.
    Example:

    $draw->setFontStyle(Imagick::STYLE_NORMAL);
    // Output: (sets text font style to normal)

    ImagickDraw::setFontWeight()
    Description: Specifies the weight of the font for text.
    Example:

    $draw->setFontWeight(700);
    // Output: (sets font weight to bold)

    ImagickDraw::setGravity()
    Description: Sets the placement gravity for text.
    Example:

    $draw->setGravity(Imagick::GRAVITY_SOUTHWEST);
    // Output: (positions text relative to the southwest corner)

    ImagickDraw::setStrokeAlpha()
    Description: Specifies the opacity of stroke outlines.
    Example:

    $draw->setStrokeAlpha(0.6);
    // Output: (sets stroke opacity to 60%)

    ImagickDraw::setStrokeColor()
    Description: Sets the color for stroke outlines.
    Example:

    $draw->setStrokeColor('blue');
    // Output: (sets stroke color to blue)

    ImagickDraw::setStrokeLineJoin()
    Description: Defines the style of corners when paths are stroked.
    Example:

    $draw->setStrokeAlpha(0.6);
    // Output: (sets stroke opacity to 60%)

    ImagickDraw::setStrokeMiterLimit()
    Description: Sets the miter limit for the stroke.
    Example:

    $draw->setStrokeMiterLimit(5);
    // Output: (sets miter limit to 5)

    ImagickDraw::setStrokeOpacity()
    Description: Defines the opacity level for stroke outlines.
    Example:

    $draw->setStrokeOpacity(0.9);
    // Output: (sets stroke opacity to 90%)
  • PHP Imagick Functions Complete Reference

    PHP Imagick Functions Complete Reference

    PHP Overview: A Beginner’s Guide to Syntax

    PHP is a versatile server-side language widely used in web development. Its straightforward syntax makes it suitable for both beginners and advanced developers. In this guide, we will explore the basic syntax of PHP. PHP scripts can be embedded within HTML using special PHP tags.

    Basic PHP Syntax

    PHP code is executed between PHP tags. The most commonly used tags are <?php ... ?>, which mark the beginning and end of PHP code. This is known as Escaping to PHP.

    <?php
        // PHP code goes here
    ?>

    These tags, also known as Canonical PHP tags, indicate to the PHP parser which parts of the document to process. Everything outside these tags is treated as plain HTML. Each PHP command must end with a semicolon (;).

    PHP Syntax Example

    <?php
        // Using echo to display a message
        echo "Greetings from PHP!";
    ?>

    Output:

    Greetings from PHP!

    Imagick::adaptiveBlurImage()
    Description: Add an adaptive blur filter to the image.
    Example:

    $image->adaptiveBlurImage(5, 3);
    // Output: (applies an adaptive blur with specified radius and sigma)

    Imagick::adaptiveResizeImage()
    Description: Resize the image according to specific dimensions.
    Example:

    $image->adaptiveResizeImage(200, 300);
    // Output: (resizes image to 200x300 pixels)

    Imagick::adaptiveSharpenImage()
    Description: Sharpen an image adaptively based on intensity.
    Example:

    $image->adaptiveThresholdImage(3, 3, 1);
    // Output: (applies adaptive threshold for localized pixel intensity control)

    Imagick::adaptiveThresholdImage()
    Description: Applies a threshold based on local intensity values.
    Example:

    $image->adaptiveThresholdImage(3, 3, 1);
    // Output: (applies adaptive threshold for localized pixel intensity control)

    Imagick::addImage()
    Description: Add a new image to the Imagick object image list.
    Example:

    $image->addImage($newImage);
    // Output: (adds $newImage to the Imagick list)

    Imagick::addNoiseImage()
    Description: Add noise to the image for texture or effect.
    Example:

    $image->addNoiseImage(Imagick::NOISE_IMPULSE);
    // Output: (applies impulse noise effect)

    Imagick::annotateImage()
    Description: Add text annotation to the image.
    Example:

    $combinedImage = $image->appendImages(true);
    // Output: (appends images vertically)

    Imagick::appendImages()
    Description: Append multiple images vertically or horizontally.
    Example:

    Single-line comment example!

    Imagick::autoLevelImage()
    Description: Automatically adjust image levels.
    Example:

    $image->autoLevelImage();
    // Output: (adjusts levels for better brightness and contrast)

    Imagick::blackThresholdImage()
    Description: Convert pixels below a threshold to black.
    Example:

    $image->blackThresholdImage('#222222');
    // Output: (sets pixels darker than the color threshold to black)

    Imagick::blueShiftImage()
    Description: Applies a moonlit or nighttime effect.
    Example:

    $image->blueShiftImage(1.5);
    // Output: (adds a blue shift effect with specified intensity)

    Imagick::blurImage()
    Description: Apply a basic blur effect to the image.
    Example:

    $image->blurImage(5, 3);
    // Output: (adds blur with specified radius and sigma)

    Imagick::borderImage()
    Description: Add a border to the image.
    Example:

    $image->borderImage('black', 5, 5);
    // Output: (adds a 5-pixel black border)

    Imagick::brightnessContrastImage()
    Description: Adjust brightness and contrast of the image.
    Example:

    $image->brightnessContrastImage(20, 30);
    // Output: (adjusts brightness by 20 and contrast by 30)

    Imagick::charcoalImage()
    Description: Simulate a charcoal sketch effect.
    Example:

    $image->charcoalImage(1, 2);
    // Output: (applies charcoal effect)

    Imagick::chopImage()
    Description: Crop and trim a specific region of the image.
    Example:

    $image->chopImage(100, 100, 50, 50);
    // Output: (removes 100x100 area at specified position)

    Imagick::commentImage()
    Description: Add a comment to the image.
    Example:

    $image->commentImage("Sample Comment");
    // Output: (adds 'Sample Comment' metadata to the image)

    Imagick::convolveImage()
    Description: Apply a custom convolution kernel to the image.
    Example:

    $image->convolveImage(array(1, 2, 1, 2, 4, 2, 1, 2, 1));
    // Output: (applies the specified convolution filter)

    Imagick::cropImage()
    Description: Crop the image to a specified region.
    Example:

    $image->cropImage(100, 100, 10, 10);
    // Output: (crops 100x100 pixels starting from (10, 10))

    Imagick::despeckleImage()
    Description: Reduce speckle noise in the image.
    Example:

    $image->despeckleImage();
    // Output: (applies despeckle filter to reduce noise)

    Imagick::displayImage()
    Description: Display the image object.
    Example:

    $image->displayImage();
    // Output: (opens image in default viewer, if available)

    Imagick::distortImage()
    Description: Distort an image using specific distortion methods.
    Example:

    $image->distortImage(Imagick::DISTORTION_PERSPECTIVE, array(0,0, 30,60, 120,60, 150,120), true);
    // Output: (applies perspective distortion)

    Imagick::edgeImage()
    Description: Enhance the edges within the image.
    Example:

    $image->edgeImage(1);
    // Output: (enhances edges with specified radius)

    Imagick::embossImage()
    Description: Apply a grayscale emboss effect.
    Example:

    $image->embossImage(1, 1);
    // Output: (adds emboss effect)

    Imagick::enhanceImage()
    Description: Improve the quality of a noisy image.
    Example:

    $image->enhanceImage();
    // Output: (enhances image by reducing noise)

    Imagick::equalizeImage()
    Description: Equalize the histogram of the image.
    Example:

    $image->equalizeImage();
    // Output: (equalizes the image contrast)

    Imagick::extentImage()
    Description: Set the size and origin of the image.
    Example:

    $image->extentImage(200, 200, -10, -10);
    // Output: (resizes image with new origin offset)

    Imagick::flattenImages()
    Description: Merge the sequence of images into one.
    Example:

    $flattenedImage = $image->flattenImages();
    // Output: (flattens multiple layers into a single image)

    Imagick::flipImage()
    Description: Create a vertically flipped image.
    Example:

    $image->flipImage();
    // Output: (flips the image vertically)

    Imagick::flopImage()
    Description: Create a horizontally flipped image
    Example:

    $image->flopImage();
    // Output: (flips the image horizontally)

    Imagick::gammaImage()
    Description: Apply gamma correction to the image.
    Example:

    $image->gammaImage(1.2);
    // Output: (adjusts gamma to 1.2)

    Imagick::getCopyright()
    Description: Return ImageMagick API copyright.
    Example:

    echo $image->getCopyright();
    // Output: (displays ImageMagick copyright)

    Imagick::getImageBluePrimary()
    Description: Get the chromaticity blue primary point.
    Example:

    print_r($image->getImageBluePrimary());
    // Output: (displays x, y values for blue primary)

    Imagick::getImageColors()
    Description: Get the number of unique colors in the image.
    Example:

    echo $image->getImageColors();
    // Output: (number of unique colors)

    Imagick::getImageColorspace()
    Description: Get the colorspace of the image.
    Example:

    echo $image->getImageColorspace();
    // Output: (colorspace type)

    Imagick::getImageChannelDepth()
    Description: Get the depth of a specific image channel.
    Example:

    echo $image->getImageChannelDepth(Imagick::CHANNEL_RED);
    // Output: (depth of the red channel)

    Imagick::getImageDepth()
    Description: Get the image depth.
    Example:

    echo $image->getImageDepth();
    // Output: (bit-depth of the image)

    Imagick::getImageFormat()
    Description: Get the format of the image.
    Example:

    echo $image->getImageFormat();
    // Output: (file format, e.g., PNG)

    Imagick::getImageGeometry()
    Description: Get width and height of the image.
    Example:

    print_r($image->getImageGeometry());
    // Output: (width and height as an associative array)

    Imagick::getImageHeight()
    Description: Get the height of the image.
    Example:

    echo $image->getImageHeight();
    // Output: (height in pixels)

    Imagick::getImageWidth()
    Description: Get the width of the image.
    Example:

    echo $image->getImageWidth();
    // Output: (width in pixels)

    Imagick::haldClutImage()
    Description: Replace colors in the image using a Hald lookup table.
    Example:

    $image->haldClutImage($clutImage);
    // Output: (replaces colors based on Hald lookup table)

    Imagick::identifyImage()
    Description: Identify an image and return its attributes.
    Example:

    print_r($image->identifyImage());
    // Output: (image metadata and attributes)

    Imagick::magnifyImage()
    Description: Scale the image up by 2x.
    Example:

    $image->magnifyImage();
    // Output: (image size increased by 2x)

    Imagick::modulateImage()
    Description: Adjust brightness, saturation, and hue.
    Example:

    $image->modulateImage(100, 150, 100);
    // Output: (adjusts brightness, saturation, and hue)

    Imagick::motionBlurImage()
    Description: Simulate motion blur in the image.
    Example:

    $image->motionBlurImage(5, 10, 45);
    // Output: (applies motion blur with specified angle)

    Imagick::negateImage()
    Description: Invert the colors of the image.
    Example:

    $image->negateImage(false);
    // Output: (inverts colors)

    Imagick::newImage()
    Description: Create a new image.
    Example:

    $image->newImage(200, 200, new ImagickPixel('red'));
    // Output: (creates a 200x200 red image)

    Imagick::normalizeImage()
    Description: Enhance the contrast by adjusting colors to span the full color range.
    Example:

    $image->normalizeImage();
    // Output: (adjusts contrast across colors)

    Imagick::oilPaintImage()
    Description: Simulate an oil painting effect.
    Example:

    $image->oilPaintImage(3);
    // Output: (applies oil paint effect with radius 3)

    Imagick::orderedPosterizeImage()
    Description: Apply ordered dithering for posterization.
    Example:

    $image->orderedPosterizeImage("o8x8");
    // Output: (reduces colors using dithering)

    Imagick::posterizeImage()
    Description: Reduce image colors to limited levels.
    Example:

    $image->posterizeImage(4, false);
    // Output: (reduces color levels to 4)

    Imagick::queryFonts()
    Description: Get the list of available fonts.
    Example:

    print_r($image->queryFonts());
    // Output: (array of font names)

    Imagick::radialBlurImage()
    Description: Apply radial blur to the image.
    Example:

    $image->radialBlurImage(5);
    // Output: (adds radial blur with 5 degrees)

    Imagick::raiseImage()
    Description: Create a 3D button effect by lightening edges.
    Example:

    $image->raiseImage(10, 10, 5, 5, true);
    // Output: (creates raised edge effect)

    Imagick::randomThresholdImage()
    Description: Change pixel values based on intensity.
    Example:

    $image->randomThresholdImage(0.4 * Imagick::getQuantum(), 0.8 * Imagick::getQuantum());
    // Output: (adjusts pixel values based on intensity threshold)

    Imagick::readImageBlob()
    Description: Read an image from a binary string.
    Example:

    $image->readImageBlob(file_get_contents("path/to/image.png"));
    // Output: (loads image from binary data)

    Imagick::recolorImage()
    Description: Apply color transformations.
    Example:

    $image->recolorImage(array(
        1.5, 0, 0,
        0, 1.2, 0,
        0, 0, 1.3
    ));
    // Output: (adjusts RGB color intensities)

    Imagick::reduceNoiseImage()
    Description: Reduce noise in an image.
    Example:

    $image->reduceNoiseImage(1);
    // Output: (smooths contours and reduces noise)

    Imagick::resampleImage()
    Description: Resample the image to a desired resolution.
    Example:

    $image->resampleImage(150, 150, Imagick::FILTER_LANCZOS, 1);
    // Output: (resamples to 150x150 dpi)

    Imagick::rollImage()
    Description: Roll image pixels horizontally and vertically.
    Example:

    $image->rollImage(10, 10);
    // Output: (shifts image by 10 pixels horizontally and vertically)

    Imagick::rotationalBlurImage()
    Description: Apply rotational blur at a given angle.
    Example:

    $image->rotationalBlurImage(10);
    // Output: (applies 10-degree rotational blur)

    Imagick::rotateImage()
    Description: Rotate the image by a specified angle.
    Example:

    $image->rotateImage(new ImagickPixel('white'), 45);
    // Output: (rotates image by 45 degrees, filling gaps with white)

    Imagick::textureImage()
    Description: Tile a texture over the image.
    Example:

    $image->textureImage($textureImage);
    // Output: (tiles $textureImage as a background)

    Imagick::thumbnailImage()
    Description: Resize the image to thumbnail dimensions.
    Example:

    $image->thumbnailImage(100, 100);
    // Output: (creates 100x100 thumbnail)

    Imagick::thresholdImage()
    Description: Change pixel values based on threshold.
    Example:

    $image->thresholdImage(0.5 * Imagick::getQuantum());
    // Output: (pixels below threshold set to black, others white)

    Imagick::transformImage()
    Description: Crop and resize the image according to geometry.
    Example:

    $image->transformImage("100x100", "200x200");
    // Output: (crops to 100x100 and resizes to 200x200)

    Imagick::transformImageColorspace()
    Description: Convert the image to a different colorspace.
    Example:

    $image->transformImageColorspace(Imagick::COLORSPACE_GRAY);
    // Output: (converts image to grayscale)

    Imagick::transposeImage()
    Description: Create a vertically mirrored image.
    Example:

    $image->transposeImage();
    // Output: (vertical mirror effect)

    Imagick::transverseImage()
    Description: Create a horizontally mirrored image.
    Example:

    $image->transverseImage();
    // Output: (horizontal mirror effect)

    Imagick::trimImage()
    Description: Trim edges of the image.
    Example:

    $image->trimImage(0);
    // Output: (trims edges with matching colors)

    Imagick::setImageChannelDepth()
    Description: Set channel depth for a specific channel.
    Example:

    $image->setImageChannelDepth(Imagick::CHANNEL_RED, 16);
    // Output: (sets red channel depth to 16 bits)

    Imagick::setImageOpacity()
    Description: Set the opacity level of the image.
    Example:

    $image->setImageOpacity(0.5);
    // Output: (sets opacity to 50%)

    Imagick::sharpenImage()
    Description: Sharpen the image with a radius and sigma.
    Example:

    $image->sharpenImage(2, 1);
    // Output: (sharpens with 2 radius and 1 sigma)

    Imagick::shaveImage()
    Description: Shave pixels off edges of the image.
    Example:

    $image->shaveImage(10, 10);
    // Output: (removes 10 pixels from each edge)

    Imagick::shearImage()
    Description: Apply a shear transformation to the image.
    Example:

    $image->shearImage(new ImagickPixel('white'), 20, 30);
    // Output: (shears image by 20x30 degrees)

    Imagick::sketchImage()
    Description: Simulate a pencil sketch effect.
    Example:

    $image->sketchImage(10, 1, 45);
    // Output: (applies sketch effect with given radius, sigma, and angle)

    Imagick::solarizeImage()
    Description: Apply a solarizing effect.
    Example:

    $image->solarizeImage(128);
    // Output: (solarizes using a threshold of 128)

    Imagick::spliceImage()
    Description: Splice a solid color into the image.
    Example:

    $image->spliceImage(10, 10, 5, 5);
    // Output: (adds a 10x10 section at coordinates 5,5)

    Imagick::spreadImage()
    Description: Randomly displace each pixel in a block.
    Example:

    $image->spreadImage(5);
    // Output: (randomly displaces pixels with a 5-pixel radius)

    Imagick::unsharpMaskImage()
    Description: Apply an unsharp mask filter.
    Example:

    $image->unsharpMaskImage(1, 0.5, 1, 0.05);
    // Output: (sharpens image with unsharp mask)

    Imagick::uniqueImageColors()
    Description: Discard duplicate colors in the image.
    Example:

    $image->uniqueImageColors();
    // Output: (removes duplicated colors)

    Imagick::vignetteImage()
    Description: Add a vignette effect to the image.
    Example:

    $image->vignetteImage(10, 20, 5, 5);
    // Output: (adds vignette with given parameters)

    Imagick::waveImage()
    Description: Apply a wave filter to the image.
    Example:

    $image->waveImage(5, 50);
    // Output: (creates a wave effect with amplitude 5, wavelength 50)

    Imagick::whiteThresholdImage()
    Description: Set pixels above threshold to white.
    Example:

    $image->whiteThresholdImage(new ImagickPixel('rgb(200, 200, 200)'));
    // Output: (pixels above threshold become white)

    Imagick::whiteThresholdImage()
    Description: Set pixels above threshold to white.
    Example:

    $image->whiteThresholdImage(new ImagickPixel('rgb(200, 200, 200)'));
    // Output: (pixels above threshold become white)

    Imagick::waveImage()
    Description: Apply a wave filter to the image.
    Example:

    $image->waveImage(5, 50);
    // Output: (creates a wave effect with amplitude 5, wavelength 50)

    Imagick::writeImage()
    Description: Write the image to a file.
    Example:

    $image->writeImage("output.png");
    // Output: (saves image to output.png)

    Imagick::getImageWidth()
    Description: Retrieve the width of the image.
    Example:

    echo $image->getImageWidth();
    // Output: (width of $image)

    Imagick::getImageHeight()
    Description: Retrieve the height of the image.
    Example:

    echo $image->getImageHeight();
    // Output: (height of $image)

    Imagick::getImageFormat()
    Description: Retrieve the format of the image.
    Example:

    echo $image->getImageFormat();
    // Output: (format of $image, e.g., PNG, JPEG)

    Imagick::getImageResolution()
    Description: Get the resolution of the image.
    Example:

    print_r($image->getImageResolution());
    // Output: (image resolution as [x, y] array)

    Imagick::setImageUnits()
    Description: Set the units of resolution for the image.
    Example:

    $image->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
    // Output: (sets resolution units to pixels per inch)

    Imagick::shadeImage()
    Description: Apply a 3D effect to the image by shading.
    Example:

    $image->shadeImage(true, 30, 30);
    // Output: (adds 3D shading effect)
  • PHP Image Processing and GD Functions Complete Reference

    PHP Image Processing and GD Functions Complete Reference

    Image processing and GD functions enable the creation and manipulation of image files across various formats, such as GIF, PNG, JPEG, WBMP, and XPM. With PHP, these functions can directly output the image to the browser. The GD library is central to implementing image functions for this purpose, though other libraries may be needed depending on the image formats involved.

    Example: This demonstrates the use of the imagecolorclosesthwb() function in PHP.

    <?php
    
    // Create a new image from a given URL
    $image = imagecreatefromgif(
    'https://www.example.com/sample-image.gif');
    
    // Display the index of the color closest to the specified hue, white, and blackness
    echo 'Hue, White, and Blackness closest color index: '
    	. imagecolorclosesthwb($image, 120, 200, 50);
    
    imagedestroy($image);
    ?>

    Output:

    Hue, White, and Blackness closest color index: 42
    The list of Image processing and GD s are given below:

    gd_info()

    Description: Retrieve information about the installed GD library.

    Example:

    print_r(gd_info());
    // Output: (array of GD library information)

    getimagesize()

    Description: Get the dimensions of an image.

    Example:

    $size = getimagesize("example.jpg");
    print_r($size);
    // Output: (displays array with width, height, and more details)

    getimagesizefromstring()

    Description: Determine the size of an image from a binary string.

    Example:

    $imageData = file_get_contents("example.jpg");
    $size = getimagesizefromstring($imageData);
    print_r($size);
    // Output: (array of image size information)

    imagealphablending()

    Description: Set the blending mode for an image.

    Example:

    $image = imagecreatetruecolor(200, 200);
    imagealphablending($image, true);
    // Output: (enables or disables blending for $image)

    imagearc()

    Description: Create an arc centered at the specified coordinates.

    Example:

    $image = imagecreatetruecolor(200, 200);
    imagearc($image, 100, 100, 150, 150, 0, 180, 0xFFFFFF);
    // Output: (draws a half-circle in the image)

    imagechar()

    Description: Draw a character horizontally on an image.

    Example:

    imagechar($image, 5, 50, 50, "A", 0xFFFFFF);
    // Output: (draws 'A' at (50, 50) on $image)

    imagecharup()

    Description: Draw a character vertically on an image.

    Example:

    imagecharup($image, 5, 50, 50, "B", 0xFFFFFF);
    // Output: (draws 'B' vertically at (50, 50) on $image)

    imagecolorallocate()

    Description: Set a color in an image.

    Example:

    $color = imagecolorallocate($image, 0, 128, 255);
    // Output: (assigns a blue color to $image)

    imagecolorallocatealpha()

    Description: Allocate color with alpha for transparency.

    Example:

    $color = imagecolorallocatealpha($image, 255, 0, 0, 50);
    // Output: (assigns a semi-transparent red color)

    imagecolorat()

    Description: Get the color of a specific pixel.

    Example:

    $color = imagecolorat($image, 10, 10);
    echo $color;
    // Output: (color index of pixel at (10, 10))

    imagecolorclosest()

    Description: Find the closest color index in the image.

    Example:

    $color = imagecolorclosest($image, 100, 100, 200);
    echo $color;
    // Output: (closest color index for the specified RGB)

    imagecolorclosestalpha()

    Description: Get the closest color with an alpha value.

    Example:

    $color = imagecolorclosestalpha($image, 100, 100, 200, 50);
    echo $color;
    // Output: (closest color index with alpha)

    imagecolorclosesthwb()

    Description: Find the hue, white, and black closest color index.

    Example:

    $color = imagecolorclosesthwb($image, 255, 0, 0);
    echo $color;
    // Output: (closest index for hue, white, and black)

    imagecolorexact()

    Description: Get the index of a specific color in the image palette.

    Example:

    $color = imagecolorexact($image, 255, 255, 255);
    echo $color;
    // Output: (color index of exact match for white)

    imagecolormatch()

    Description: Match the palette version colors of an image to a true-color version.

    Example:

    imagecolormatch($image1, $image2);
    // Output: (matches colors of $image1 to $image2)

    imagecolorresolve()

    Description: Get the specified color or closest possible in the palette.

    Example:

    $color = imagecolorresolve($image, 255, 100, 50);
    echo $color;
    // Output: (index of exact or nearest color)

    imagecolorresolvealpha()

    Description: Find specified color and alpha value or closest alternative.

    Example:

    $color = imagecolorresolvealpha($image, 255, 100, 50, 50);
    echo $color;
    // Output: (index of color with alpha)

    imagecolorset()

    Description: Set the color for a specified palette index.

    Example:

    imagecolorset($image, 5, 100, 50, 150);
    // Output: (sets color at index 5 in palette)

    imagecolorsforindex()

    Description: Get the colors at a specified index.

    Example:

    $color = imagecolorsforindex($image, 5);
    print_r($color);
    // Output: (RGB array of colors at index 5)

    imagecolorstotal()

    Description: Find the number of colors in an image’s palette.

    Example:

    echo imagecolorstotal($image);
    // Output: (total number of colors in the palette)

    imagecolortransparent()

    Description: Define a color as transparent in the image.

    Example:

    imagecolortransparent($image, $color);
    // Output: (sets $color as transparent)

    imageconvolution()

    Description: Apply a convolution matrix to the image.

    Example:

    $matrix = array(
      array(0, -1, 0),
      array(-1, 4, -1),
      array(0, -1, 0)
    );
    imageconvolution($image, $matrix, 1, 127);
    // Output: (applies convolution effect)

    imagecopy()

    Description: Copy all or part of an image.

    Example:

    imagecopy($image, $src, 0, 0, 0, 0, 100, 100);
    // Output: (copies $src onto $image)

    imagecopymerge()

    Description: Copy and merge an image with transparency.

    Example:

    imagecopymerge($image, $src, 0, 0, 0, 0, 100, 100, 50);
    // Output: (merges $src onto $image with 50% opacity)

    imagecopymergegray()

    Description: Merge a grayscale version of part of an image.

    Example:

    echo IntlChar::isspace(" ");
    // Output: 1

    imagecreate()

    Description: Create a new palette-based image.

    Example:

    $image = imagecreate(200, 200);
    // Output: (creates 200x200 image with color palette)

    imagecreatetruecolor()

    Description: Create a new true-color image.

    Example:

    $image = imagecreatetruecolor(200, 200);
    // Output: (creates 200x200 true-color image)

    imagecrop()

    Description: Crop the image to a specified rectangle.

    Example:

    $image = imagecrop($image, array("x"=>50, "y"=>50, "width"=>100, "height"=>100));
    // Output: (crops $image to the given dimensions)

    imagedashedline()

    Description: Draw a dashed line in the image.

    Example:

    imagedashedline($image, 0, 0, 200, 200, 0xFFFFFF);
    // Output: (draws dashed line from (0, 0) to (200, 200))

    imagefilledarc()

    Description: Draw a filled partial arc.

    Example:

    imagefilledarc($image, 100, 100, 100, 100, 0, 180, 0x0000FF, IMG_ARC_PIE);
    // Output: (draws a half-circle arc filled in blue)

    imagefilledrectangle()

    Description: Draw a filled rectangle.

    Example:

    imagefilledrectangle($image, 0, 0, 100, 50, 0x000000);
    // Output: (draws black rectangle at specified area)

    imagefilledarc()

    Description: Draw a filled partial arc.

    Example:

    imagefilledarc($image, 100, 100, 100, 100, 0, 180, 0x0000FF, IMG_ARC_PIE);
    // Output: (draws a half-circle arc filled in blue)

    imagelayereffect()

    Description: Set alpha blending flag for layering effects.

    Example:

    imagelayereffect($image, IMG_EFFECT_OVERLAY);
    // Output: (enables overlay effect on $image)

    imagepolygon()

    Description: Draw a polygon on the image.

    Example:

    $points = array(50, 0, 100, 100, 0, 100);
    imagepolygon($image, $points, 3, 0xFFFFFF);
    // Output: (draws white triangle)

    imagerectangle()

    Description: Draw a rectangle in the image.

    Example:

    imagerectangle($image, 10, 10, 100, 50, 0xFF0000);
    // Output: (draws red rectangle at specified area)

    imagetruecolortopalette()

    Description: Convert a true-color image to a palette image.

    Example:

    imagetruecolortopalette($image, false, 256);
    // Output: (converts image to 256 color palette)

    imagesy()

    Description: Return the height of an image.

    Example:

    echo imagesy($image);
    // Output: (height of $image)

    imagesx()

    Description: Return the width of an image.

    Example:

    echo imagesx($image);
    // Output: (width of $image)
  • PHP IntlChar Functions

    The IntlChar class in PHP provides a set of static methods for character processing, conforming to the Unicode standard.

    IntlChar::charAge(): Get the Unicode version in which the code point was first designated.

    IntlChar::charAge(int $codepoint): array;

    IntlChar::charDigitValue(): Get the decimal digit value of a code point.

    IntlChar::charDigitValue(int $codepoint): int;

    IntlChar::charDirection(): Get the bidirectional category value for a code point.

    IntlChar::charDirection(int $codepoint): int;

    IntlChar::charFromName(): Find a Unicode character by its name.

    IntlChar::charFromName(string $name, int $nameChoice = IntlChar::UNICODE_CHAR_NAME): int;

    IntlChar::charMirror(): Get the “mirror image” of a code point.

    IntlChar::charMirror(int $codepoint): int;

    IntlChar::charName(): Get the Unicode name for a code point.

    IntlChar::charName(int $codepoint, int $nameChoice = IntlChar::UNICODE_CHAR_NAME): string;

    IntlChar::charScript(): Get the script value for a code point.

    IntlChar::charScript(int $codepoint): int;

    IntlChar::charType(): Get the general category value for a code point.

    IntlChar::charType(int $codepoint): int;

    IntlChar::digit(): Get the decimal digit value of a numeric code point.

    disk_free_space($directory);

    IntlChar::enumCharNames(): Enumerate all assigned Unicode character names.

    IntlChar::enumCharNames(int $start, int $end, callable $callback, int $nameChoice = IntlChar::UNICODE_CHAR_NAME);

    IntlChar::enumCharTypes(): Enumerate all code points with the same general category.

    IntlChar::enumCharTypes(callable $callback);

    IntlChar::foldCase(): Perform Unicode simple case folding.

    IntlChar::foldCase(int $codepoint, int $options = IntlChar::FOLD_CASE_DEFAULT): int;

    IntlChar::forDigit(): Get the numeric value of a Unicode digit.

    IntlChar::forDigit(int $digit, int $radix = 10): int;

    IntlChar::getBidiPairedBracket(): Get the paired bracket character for a code point.

    IntlChar::getBidiPairedBracket(int $codepoint): int;

    IntlChar::getBlockCode(): Get the Unicode block value for a code point.

    IntlChar::getBlockCode(int $codepoint): int;

    IntlChar::getCombiningClass(): Get the combining class value for a code point.

    IntlChar::getCombiningClass(int $codepoint): int;

    IntlChar::getFC_NFKC_Closure(): Get the FC_NFKC_Closure property value for a code point.

    IntlChar::getFC_NFKC_Closure(int $codepoint): string;

    IntlChar::getIntPropertyMaxValue(): Get the maximum value for a Unicode property.

    IntlChar::getIntPropertyMaxValue(int $property): int;

    IntlChar::getIntPropertyMinValue(): Get the minimum value for a Unicode property.

    IntlChar::getIntPropertyMinValue(int $property): int;

    IntlChar::getIntPropertyValue(): Get the integer value for a Unicode property.

    IntlChar::getIntPropertyValue(int $codepoint, int $property): int;

    IntlChar::getNumericValue(): Get the numeric value for a code point.

    IntlChar::getNumericValue(int $codepoint): float;

    IntlChar::getPropertyEnum(): Get the integer value for a property alias.

    IntlChar::getPropertyEnum(string $alias): int;

    IntlChar::getPropertyName(): Get the property name for a property value.

    IntlChar::getPropertyName(int $property, int $nameChoice = IntlChar::LONG_PROPERTY_NAME): string;

    IntlChar::getPropertyValueName(): Get the name for a property value.

    IntlChar::getPropertyValueName(int $property, int $value, int $nameChoice = IntlChar::LONG_PROPERTY_NAME): string;

    IntlChar::getUnicodeVersion(): Get the Unicode version.

    IntlChar::getUnicodeVersion(): array;

    IntlChar::hasBinaryProperty(): Check if a code point has a binary property.

    IntlChar::hasBinaryProperty(int $codepoint, int $property): bool;

    IntlChar::hasBinaryProperty(): Check if a code point has a binary property.

    IntlChar::hasBinaryProperty(int $codepoint, int $property): bool;

    IntlChar::isalnum(): Check if a code point is an alphanumeric character.

    IntlChar::isalnum(int $codepoint): bool;

    IntlChar::isalpha(): Check if a code point is an alphabetic character.

    IntlChar::isalpha(int $codepoint): bool;

    IntlChar::isbase(): Check if a code point is a base character.

    IntlChar::isbase(int $codepoint): bool;

    IntlChar::isblank(): Check if a code point is a blank character.

    IntlChar::isblank(int $codepoint): bool;

    IntlChar::iscntrl(): Check if a code point is a control character.

    IntlChar::iscntrl(int $codepoint): bool;

    IntlChar::isdefined(): Check if a code point is a defined character.

    IntlChar::isdefined(int $codepoint): bool;

    IntlChar::isdigit(): Check if a code point is a digit character.

    IntlChar::isdigit(int $codepoint): bool;

    fileowner($filename);

    fileowner($filename);

    IntlChar::isgraph(): Check if a code point is a graphic character.

    IntlChar::isgraph(int $codepoint): bool;

    IntlChar::isgraph(int $codepoint): bool;

    IntlChar::isgraph(int $codepoint): bool;

    IntlChar::isIDIgnorable(): Check if a code point is an ignorable character.

    IntlChar::isIDIgnorable(int $codepoint): bool;

    IntlChar::isIDPart(): Check if a code point can be part of an identifier.

    IntlChar::isIDPart(int $codepoint): bool;

    fnmatch(): Matches a filename or string against a specified pattern.

    fnmatch($pattern, $string, $flags);

    IntlChar::isIDStart(): Check if a code point can start an identifier.

    IntlChar::isIDStart(int $codepoint): bool;

    IntlChar::isISOControl(): Check if a code point is an ISO control character.

    IntlChar::isISOControl(int $codepoint): bool;

    IntlChar::islower(): Check if a code point is a lowercase character.

    IntlChar::islower(int $codepoint): bool;

    IntlChar::islower(int $codepoint): bool

    IntlChar::islower(int $codepoint): bool;

    IntlChar::isMirrored(): Check if a code point has the Bidi_Mirrored property.

    IntlChar::isMirrored(int $codepoint): bool;

    IntlChar::isprint(): Check if a code point is a printable character.

    fseek($handle, $offset, $whence);

    IntlChar::ispunct(): Check if a code point is a punctuation character.

    IntlChar::ispunct(int $codepoint): bool;

    IntlChar::isspace(): Check if a code point is a space character.

    IntlChar::isspace(int $codepoint): bool;

    IntlChar::isUWhiteSpace(): Check if a code point has the White_Space property.

    IntlChar::isUWhiteSpace(int $codepoint): bool;
  • PHP Intl Functions

    The intl extension in PHP provides capabilities for internationalization (i18n) and localization (l10n), supporting features like locale-aware formatting, transliteration, and message formatting. Below is a list of key functions provided by the intl extension.

    Collator

    1. collator_asort(): Sort array maintaining index association.
    collator_asort(Collator $coll, array &$arr, int $sort_flag = Collator::SORT_REGULAR): bool;

    chgrp(): Changes the group ownership of a file.

    chgrp($filename, $group);

    collator_compare(): Compare two Unicode strings.

    collator_compare(Collator $coll, string $str1, string $str2): int;

    collator_get_attribute(): Get an attribute value.

    collator_get_attribute(Collator $coll, int $attr): int|false;

    collator_get_error_code(): Get collator’s last error code.

    collator_get_error_code(Collator $coll): int;

    collator_get_error_message(): Get text for collator’s last error code.

    collator_get_error_message(Collator $coll): string;

    collator_get_locale(): Get the locale name of the collator.

    collator_get_locale(Collator $coll, int $type): string|false;

    collator_get_sort_key(): Get sorting key for a string.

    collator_get_sort_key(Collator $coll, string $string): string|false;

    collator_get_strength(): Get the collator’s strength.

    collator_get_strength(Collator $coll): int;

    collator_set_attribute(): Set an attribute value.

    collator_set_attribute(Collator $coll, int $attr, int $val): bool;

    collator_set_strength(): Set the collator’s strength.

    collator_set_strength(Collator $coll, int $strength): bool;

    collator_sort(): Sort an array.

    collator_sort(Collator $coll, array &$arr, int $sort_flag = Collator::SORT_REGULAR): bool;

    collator_sort_with_sort_keys(): Sort array using specified sort keys.

    collator_sort_with_sort_keys(Collator $coll, array &$arr): bool;

    NumberFormatter

    numfmt_create(): Create a number formatter.

    numfmt_create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter;

    numfmt_format(): Format a number.

    numfmt_format(NumberFormatter $fmt, int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false;

    numfmt_format_currency(): Format a currency value.

    numfmt_format_currency(NumberFormatter $fmt, float $value, string $currency): string|false;

    numfmt_get_attribute(): Get an attribute value.

    fgetcsv($handle, $length, $delimiter, $enclosure, $escape);

    fgets(): Gets a line from a file pointer.

    numfmt_get_attribute(NumberFormatter $fmt, int $attr): int|float|false;

    numfmt_get_error_code(): Get formatter’s last error code.

    numfmt_get_error_code(NumberFormatter $fmt): int;

    numfmt_get_error_message(): Get text for formatter’s last error code.

    numfmt_get_error_message(NumberFormatter $fmt): string;

    numfmt_get_locale(): Get the locale name of the formatter.

    numfmt_get_locale(NumberFormatter $fmt, int $type): string|false;

    numfmt_get_pattern(): Get formatter pattern.

    file_exists($filename);

    numfmt_get_symbol(): Get a symbol value.

    numfmt_get_symbol(NumberFormatter $fmt, int $attr): string|false;

    numfmt_get_text_attribute(): Get a text attribute value.

    numfmt_get_text_attribute(NumberFormatter $fmt, int $attr): string|false;

    numfmt_parse(): Parse a number.

    numfmt_parse(NumberFormatter $fmt, string $value, int $type = NumberFormatter::TYPE_DOUBLE, &$position = null): int|float|false;

    numfmt_parse_currency(): Parse a currency number.

    numfmt_parse_currency(NumberFormatter $fmt, string $value, string &$currency, &$position = null): float|false;

    numfmt_set_attribute(): Set an attribute value.

    numfmt_set_attribute(NumberFormatter $fmt, int $attr, int|float $value): bool;

    numfmt_set_pattern(): Set formatter pattern.

    numfmt_set_pattern(NumberFormatter $fmt, string $pattern): bool;

    numfmt_set_symbol(): Set a symbol value.

    numfmt_set_symbol(NumberFormatter $fmt, int $attr, string $value): bool;

    MessageFormatter

    msgfmt_create(): Create a message formatter.

    msgfmt_create(string $locale, string $pattern): ?MessageFormatter;

    msgfmt_format(): Format the message.

    msgfmt_format(MessageFormatter $fmt, array $args): string|false;

    msgfmt_format_message(): Quick format message.

    msgfmt_format_message(string $locale, string $pattern, array $args): string|false;

    msgfmt_get_error_code(): Get formatter’s last error code.

    msgfmt_get_error_code(MessageFormatter $fmt): int;

    msgfmt_get_error_message(): Get text for formatter’s last error code.

    msgfmt_get_error_message(MessageFormatter $fmt): string;

    msgfmt_get_locale(): Get the locale name of the formatter.

    msgfmt_get_locale(MessageFormatter $fmt): string|false;

    msgfmt_get_locale(MessageFormatter $fmt): string|false;

    msgfmt_get_locale(MessageFormatter $fmt): string|false;

    msgfmt_get_pattern(): Get formatter pattern.

    msgfmt_get_pattern(MessageFormatter $fmt): string|false;

    msgfmt_parse(): Parse input string.

    msgfmt_parse(MessageFormatter $fmt, string $value): array|false;

    msgfmt_parse_message(): Quick parse input string.

    msgfmt_parse_message(string $locale, string $pattern, string $source): array|false;

    msgfmt_set_pattern(): Set formatter pattern.

    msgfmt_set_pattern(MessageFormatter $fmt, string $pattern): bool;

    Normalizer

    normalizer_is_normalized(): Checks if the provided string is already in the specified normalization form.

    normalizer_is_normalized(string $input, int $form = Normalizer::FORM_C): bool;

    normalizer_normalize(): Normalizes the input provided and returns the normalized string.

    normalizer_normalize(string $input, int $form = Normalizer::FORM_C): string|false;

    ResourceBundle

    resourcebundle_create(): Create a resource bundle.

    resourcebundle_create(string $locale, string $bundlename, bool $fallback): ?ResourceBundle;

    resourcebundle_count(): Get the number of elements in the bundle.

    resourcebundle_count(ResourceBundle $bundle): int;

    resourcebundle_get(): Get data from the bundle.

    resourcebundle_get(ResourceBundle $bundle, int|string $index): mixed;

    resourcebundle_get_error_message(): Get text for bundle’s last error code.

    resourcebundle_get_error_message(ResourceBundle $bundle): string;

    resourcebundle_get_error_code(): Get bundle’s last error code.

    resourcebundle_get_error_code(ResourceBundle $bundle): int;

    resourcebundle_locales(): Get supported locales.

    resourcebundle_locales(string $bundlename): array|false;
  • PHP Filesystem Functions Complete Reference

    PHP Filesystem Functions Complete Reference

    basename()
    Description: Return the filename from a given path.
    Example:

    echo basename("/path/to/file.txt");
    // Output: file.txt

    chgrp()
    Description: Change the user group of a specified file.
    Example:

    chgrp("example.txt", "users");
    // Output: (changes the group to 'users')

    chmod()
    Description: Modify file permissions to a specified mode.
    Example:

    chmod("example.txt", 0755);
    // Output: (sets permissions to 755)

    chown()
    Description: Assign a new owner to a specified file.
    Example:

    chown("example.txt", "newowner");
    // Output: (changes the owner to 'newowner')

    copy()
    Description: Create a copy of a specified file.
    Example:

    copy("source.txt", "copy.txt");
    // Output: (creates a duplicate of 'source.txt' as 'copy.txt')

    dirname()
    Description: Get the directory path from a file path.
    Example:

    echo dirname("/path/to/file.txt");
    // Output: /path/to

    disk_free_space()
    Description: Determine the free space in a specified directory.
    Example:

    echo disk_free_space("/");
    // Output: (returns free space in bytes)

    disk_total_space()
    Description: Retrieve the total storage capacity of a specified directory.
    Example:

    echo disk_total_space("/");
    // Output: (returns total space in bytes)

    fclose()
    Description: Close a file pointer that is currently open.
    Example:

    $file = fopen("example.txt", "r");
    fclose($file);
    // Output: (closes 'example.txt')

    feof()
    Description: Check if the end-of-file has been reached on a file pointer.
    Example:

    $file = fopen("example.txt", "r");
    while (!feof($file)) {
        echo fgets($file);
    }
    fclose($file);
    // Output: (reads until end of file)

    fflush()
    Description: Flush the output buffer to an open file.
    Example:

    $file = fopen("example.txt", "a");
    fwrite($file, "New content");
    fflush($file);
    fclose($file);
    // Output: (writes 'New content' and flushes buffer)

    fgetc()
    Description: Retrieve a single character from an open file.
    Example:

    $file = fopen("example.csv", "w");
    fputcsv($file, ["Name", "Age", "City"]); // Writes CSV line
    fclose($file);

    fgets()
    Description: Read a line from a file pointer.
    Example:

    $file = fopen("example.txt", "r");
    echo fgets($file);
    fclose($file);
    // Output: (reads and outputs the first line)

    fgetss()
    Description: Read a line from a file while stripping out HTML and PHP tags.
    Example:

    $file = fopen("example.txt", "r");
    echo fgetss($file);
    fclose($file);
    // Output: (outputs the line without HTML tags)

    file_exists()
    Description: Check if a file or directory exists.
    Example:

    echo file_exists("example.txt") ? "Exists" : "Does not exist";
    // Output: Exists or Does not exist

    file_get_contents()
    Description: Read the entire file content into a string.
    Example:

    echo file_get_contents("example.txt");
    // Output: (displays file contents as a string)

    file_put_contents()
    Description: Write a string to a file.
    Example:

    file_put_contents("example.txt", "Some content");
    // Output: (writes 'Some content' to 'example.txt')

    fileatime()
    Description: Retrieve the last access time of a specified file.
    Example:

    echo date("F d Y H:i:s", fileatime("example.txt"));
    // Output: (displays last access date and time)

    filesize()
    Description: Get the size of a specified file in bytes.
    Example:

    echo filesize("example.txt");
    // Output: (file size in bytes)

    filectime()
    Description: Get the last change time of a specified file.
    Example:

    echo date("F d Y H:i:s", filectime("example.txt"));
    // Output: (displays last change date and time)

    filemtime()
    Description:Return the last modified time of a specified file.
    Example:

    echo date("F d Y H:i:s", filemtime("example.txt"));
    // Output: (displays last modified date and time)

    fileperms()
    Description: Retrieve the permissions for a file or directory.
    Example:

    echo substr(sprintf('%o', fileperms("example.txt")), -4);
    // Output: (displays permissions, e.g., 0755)

    filesize()
    Description: Get the size of a specified file in bytes.
    Example:

    echo filesize("example.txt");
    // Output: (file size in bytes)

    filetype()
    Description: Determine the type of file.
    Example:

    echo filetype("example.txt");
    // Output: file or dir

    flock()
    Description: Apply a portable advisory lock on the file.
    Example:

    $file = fopen("example.txt", "r+");
    if (flock($file, LOCK_EX)) {
        // Do something
        flock($file, LOCK_UN);
    }
    fclose($file);
    // Output: (locks and unlocks the file)

    fopen()
    Description: Open a file or URL.
    Example:

    $file = fopen("example.txt", "r");
    // Output: (opens 'example.txt' for reading)

    fpassthru()
    Description: Output all remaining data from a file pointer until EOF.
    Example:

    The variable is an integer.
    The variable is a string.

    fputcsv()
    Description: Write a line of CSV formatted data to a file.
    Example:

    $file = fopen("data.csv", "w");
    fputcsv($file, ["Name", "Age"]);
    fclose($file);
    // Output: (writes "Name, Age" to 'data.csv')

    fread()
    Description: Read up to a specified length of bytes from a file.
    Example:

    $file = fopen("example.txt", "r");
    echo fread($file, 100);
    fclose($file);
    // Output: (displays first 100 bytes)

    fseek()
    Description: Set the file pointer to a specified position.
    Example:

    $file = fopen("example.txt", "r");
    fseek($file, 5);
    echo fgets($file);
    fclose($file);
    // Output: (displays content starting from position 5)

    fstat()
    Description: Return information about an open file.
    Example:

    $file = fopen("example.txt", "r");
    print_r(fstat($file));
    fclose($file);
    // Output: (displays file info array)

    ftell()
    Description: Get the current position of the file pointer.
    Example:

    $file = fopen("example.txt", "r");
    echo ftell($file);
    fclose($file);
    // Output: (current file pointer position)

    ftruncate()
    Description: Truncate a file to a specified length.
    Example:

    $file = fopen("example.txt", "r+");
    ftruncate($file, 50);
    fclose($file);
    // Output: (shortens file to 50 bytes)

    fwrite()
    Description: Write a string to a file.
    Example:

    $file = fopen("example.txt", "w");
    fwrite($file, "PHP Filesystem Functions");
    fclose($file);
    // Output: (writes text to 'example.txt')

    is_dir()
    Description: Check if a path is a directory.
    Example:

    echo is_dir("/path/to/directory") ? "Directory" : "Not a directory";
    // Output: Directory or Not a directory

    is_executable()
    Description: Determine if a file is executable.
    Example:

    echo is_executable("script.sh") ? "Executable" : "Not executable";
    // Output: Executable or Not executable

    is_file()
    Description: Verify if a path is a regular file.
    Example:

    echo is_file("example.txt") ? "File" : "Not a file";
    // Output: File or Not a file

    is_link()
    Description: Check if a specified file is a symbolic link.
    Example:

    echo is_link("example_link") ? "Symbolic link" : "Not a symbolic link";
    // Output: Symbolic link or Not a symbolic link

    is_readable()
    Description: Determine if a file exists and is readable.
    Example:

    echo is_readable("example.txt") ? "Readable" : "Not readable";
    // Output: Readable or Not readable

    is_uploaded_file()
    Description: Check if a file was uploaded via HTTP POST.
    Example:

    echo is_uploaded_file($_FILES['file']['tmp_name']) ? "Uploaded" : "Not uploaded";
    // Output: Uploaded or Not uploaded

    is_writable()
    Description: Verify if a file is writable.
    Example:

    echo is_writable("example.txt") ? "Writable" : "Not writable";
    // Output: Writable or Not writable

    link()
    Description: Create a hard link for a specified target.
    Example:

    link("target.txt", "hardlink.txt");
    // Output: (creates a hard link 'hardlink.txt' pointing to 'target.txt')

    lstat()
    Description: Retrieve information about a file or symbolic link.
    Example:

    print_r(lstat("example.txt"));
    // Output: (array of file or symbolic link information)

    popen()
    Description: Open a pipe to a specified command.
    Example:

    $pipe = popen("ls", "r");
    // Output: (opens a pipe to list directory contents)

    pclose()
    Description: Close a pipe opened by popen().
    Example:

    $pipe = popen("ls", "r");
    pclose($pipe);
    // Output: (closes the pipe to the command 'ls')

    pathinfo()
    Description: Get information about a path as an associative array or string.
    Example:

    print_r(pathinfo("example.txt"));
    // Output: (displays path info, e.g., directory, basename, extension)

    readfile()
    Description: Read a file and output it directly to the buffer.
    Example:

    readfile("example.txt");
    // Output: (displays contents of 'example.txt')

    rename()
    Description: Rename a file or directory.
    Example:

    rename("oldname.txt", "newname.txt");
    // Output: (changes 'oldname.txt' to 'newname.txt')

    realpath()
    Description: Return the canonical absolute pathname.
    Example:

    echo realpath("example.txt");
    // Output: (full path to 'example.txt')

    rewind()
    Description: Set the file pointer to the beginning of a file.
    Example:

    $file = fopen("example.txt", "r");
    rewind($file);
    fclose($file);
    // Output: (moves file pointer to start)

    stat()
    Description: Retrieve detailed information about a file.
    Example:

    print_r(stat("example.txt"));
    // Output: (array of file statistics)

    symlink()
    Description: Create a symbolic link pointing to a specified target.
    Example:

    symlink("target.txt", "symbolic_link.txt");
    // Output: (creates symbolic link 'symbolic_link.txt' to 'target.txt')

    tmpfile()
    Description: Create a temporary file in read-write mode.
    Example:

    $temp = tmpfile();
    fwrite($temp, "Temporary data");
    fclose($temp);
    // Output: (creates and closes a temporary file)

    touch()
    Description: Set the access and modification times for a file.
    Example:

    touch("example.txt");
    // Output: (updates 'example.txt' timestamp)

    unlink()
    Description: Delete a file.
    Example:

    unlink("example.txt");
    // Output: (removes 'example.txt')
  • PHP Math Functions Complete Reference

    PHP Math Functions Complete Reference

    PHP Math Functions

    PHP includes a range of predefined mathematical functions that facilitate operations on integer and float types. These functions are integrated into the PHP core and require no installation.

    Example: Using the decbin() function in PHP:

    <?php
    echo decbin(12);
    ?>

    abs()
    Description: Return the absolute (positive) value of a number.
    Example:

    echo abs(-10);
    // Output: 10

    acos()
    Description: Find the arc cosine of a number, returning the result in radians.
    Example:

    echo acos(0.5);
    // Output: 1.0471975511966

    acosh()
    Description: Calculate the inverse hyperbolic cosine of a number.
    Example:

    echo acosh(2);
    // Output: 1.3169578969248

    asin()
    Description: Calculate the arc sine of a number in radians.
    Example:

    echo asin(0.5);
    // Output: 0.5235987755983

    asinh()
    Description: Find the inverse hyperbolic sine of a number
    Example:.

    echo asinh(1);
    // Output: 0.88137358701954

    atan2()
    Description: Calculate the arc tangent of two numbers x and y.
    Example:

    echo atan2(1, 1);
    // Output: 0.78539816339745

    atan()
    Description: Return the arc tangent of a number, result in radians.
    Example:

    echo atan(1);
    // Output: 0.78539816339745

    atanh()
    Description: Find the inverse hyperbolic tangent of a number.
    Example:

    $file = fopen("example.txt", "r");
    echo fgets($file); // Outputs one line
    fclose($file);

    base_convert()
    Description: Convert a number from one base to another.
    Example:

    echo base_convert("A1", 16, 2);
    // Output: 10100001

    bindec()
    Description: Convert a binary string to its decimal equivalent.
    Example:

    echo bindec("1101");
    // Output: 13

    ceil()
    Description: Round a number up to the nearest integer.
    Example:

    echo ceil(4.3);
    // Output: 5

    cos()
    Description: Find the cosine of a number (in radians).
    Example:

    echo cos(1);
    // Output: 0.54030230586814

    cosh()
    Description: Calculate the hyperbolic cosine of a number.
    Example:

    echo cosh(1);
    // Output: 1.5430806348152

    decbin()
    Description: Convert a decimal number to binary.
    Example:

    echo decbin(12);
    // Output: 1100

    dechex()
    Description: Convert a decimal number to hexadecimal.
    Example:

    echo dechex(255);
    // Output: ff

    decoct()
    Description: Convert a decimal number to octal.
    Example:

    echo decoct(15);
    // Output: 17

    deg2rad()
    Description: Convert degrees to radians.
    Example:

    echo deg2rad(180);
    // Output: 3.1415926535898

    exp()
    Description: Calculate e raised to the power of a given number.
    Example:

    echo exp(2);
    // Output: 7.3890560989306

    expm1()
    Description: Calculate e raised to the power of a given number minus one.
    Example:

    echo expm1(1);
    // Output: 1.718281828459

    hypot()
    Description: Returns the square root of the sum of squares of two numbers.
    Example:

    echo hypot(3, 4);
    // Output: 5

    fmod()
    Description: Calculate the remainder of a division (modulo operation).
    Example:

    echo fmod(5.7, 1.3);
    // Output: 0.5

    hexdec()
    Description: Convert a hexadecimal string to its decimal equivalent.
    Example:

    echo hexdec("ff");
    // Output: 255

    hypot()
    Description: Calculate the length of the hypotenuse of a right-angled triangle.
    Example:

    echo hypot(3, 4);
    // Output: 5

    intdiv()
    Description: Calculate the integer quotient of the division of two numbers.
    Example:

    echo intdiv(7, 3);
    // Output: 2

    is_finite()
    Description: Check if a number is finite.
    Example:

    echo is_finite(1.2e308) ? "Finite" : "Infinite";
    // Output: Finite

    is_infinite()
    Description: Check if a number is infinite.
    Example:

    echo is_infinite(1.2e308 * 10) ? "Infinite" : "Finite";
    // Output: Infinite

    is_nan()
    Description: Check if a value is ‘not a number’.
    Example:

    echo is_nan(acos(2)) ? "Not a number" : "Number";
    // Output: Not a number

    is_readable()
    Description: Determine if a file exists and is readable.
    Example:

    echo is_readable("example.txt") ? "Readable" : "Not readable";
    // Output: Readable or Not readable

    is_uploaded_file()
    Description: Check if a file was uploaded via HTTP POST.
    Example:

    echo is_uploaded_file($_FILES['file']['tmp_name']) ? "Uploaded" : "Not uploaded";
    // Output: Uploaded or Not uploaded

    is_writable()
    Description: Verify if a file is writable.
    Example:

    echo is_writable("example.txt") ? "Writable" : "Not writable";
    // Output: Writable or Not writable

    link()
    Description: Create a hard link for a specified target.
    Example:

    link("target.txt", "hardlink.txt");
    // Output: (creates a hard link 'hardlink.txt' pointing to 'target.txt')

    lstat()
    Description: Retrieve information about a file or symbolic link.
    Example:

    print_r(lstat("example.txt"));
    // Output: (array of file or symbolic link information)

    mkdir()
    Description: Create a new directory with the specified path.
    Example:

    mkdir("new_folder");
    // Output: (creates 'new_folder' directory)

    pathinfo()
    Description: Get information about a path as an associative array or string.
    Example:

    print_r(pathinfo("example.txt"));
    // Output: (displays path info, e.g., directory, basename, extension)

    pclose()
    Description: Close a pipe opened by popen().
    Example:

    $pipe = popen("ls", "r");
    pclose($pipe);
    // Output: (closes the pipe to the command 'ls')

    popen()
    Description: Open a pipe to a specified command.
    Example:

    $pipe = popen("ls", "r");
    // Output: (opens a pipe to list directory contents)

    readfile()
    Description: Read a file and output it directly to the buffer.
    Example:

    readfile("example.txt");
    // Output: (displays contents of 'example.txt')

    realpath()
    Description: Return the canonical absolute pathname.
    Example:

    echo realpath("example.txt");
    // Output: (full path to 'example.txt')

    rewind()
    Description: Set the file pointer to the beginning of a file.
    Example:

    $file = fopen("example.txt", "r");
    rewind($file);
    fclose($file);
    // Output: (moves file pointer to start)

    stat()
    Description: Retrieve detailed information about a file.
    Example:

    print_r(stat("example.txt"));
    // Output: (array of file statistics)

    symlink()
    Description: Create a symbolic link pointing to a specified target.v Example:

    symlink("target.txt", "symbolic_link.txt");
    // Output: (creates symbolic link 'symbolic_link.txt' to 'target.txt')

    tmpfile()
    Description: Create a temporary file in read-write mode.
    Example:

    $temp = tmpfile();
    fwrite($temp, "Temporary data");
    fclose($temp);
    // Output: (creates and closes a temporary file)

    touch()
    Description: Set the access and modification times for a file.
    Example:

    touch("example.txt");
    // Output: (updates 'example.txt' timestamp)
  • PHP String Functions Complete Reference

    PHP String Functions Complete Reference

    The predefined math functions in PHP are used to handle mathematical operations with integer and float types. These math functions are built into PHP and do not require any additional installation.

    Installation: These functions do not require any special installation. The complete list of PHP math functions is given below:

    Example: A program illustrating the decbin() function in PHP:

    <?php
    echo decbin(45);
    ?>

    Output:

    101101
    List of Common PHP String Functions

    addcslashes()

    Description: Inserts backslashes before specified characters in a string.

    Example:

    echo addcslashes("Hello, World!", 'o');
    // Output: Hell\o, W\orld!

    addslashes()

    Description: Escapes special characters by adding backslashes.
    Example:

    echo addslashes("Hello 'World'");
    // Output: Hello \'World\'

    bin2hex()

    Description: Converts a string to hexadecimal representation.
    Example:

    echo bin2hex("Hi");
    // Output: 4869

    chop()

    Description: Removes whitespace or specified characters from the end of a string.
    Example:

    echo chop("Hello World!  ");
    // Output: Hello World!

    chr()

    Description: Converts ASCII value to a character.
    Example:

    echo chr(65);
    // Output: A

    chunk_split()

    Description: Splits a string into smaller chunks.
    Example:

    echo chunk_split("abcdef", 2, "-");
    // Output: ab-cd-ef-

    convert_uudecode()

    Description: Decodes a uuencoded string.
    Example:

    $encoded = convert_uuencode("Hello");
    echo convert_uudecode($encoded);
    // Output: Hello

    convert_uuencode()

    Description: Encodes a string using the uuencode algorithm.
    Example:

    echo convert_uuencode("Hello");
    // Output: 0=&5S=`IT

    count_chars()

    Description: Returns information about character frequencies in a string.
    Example:

    print_r(count_chars("Hello", 1));
    // Output: Array ( [72] => 1 [101] => 1 [108] => 2 [111] => 1 )

    crc32()

    Description: Calculates the CRC32 polynomial of a string.
    Example:

    echo crc32("Hello");
    // Output: 907060870

    crypt()

    Description: One-way string hashing using algorithms like DES, Blowfish, or MD5.
    Example:

    echo crypt("mypassword", "salt");
    // Output: saGng5vH/kMmQ

    password_hash()

    Description: Creates a password hash using the bcrypt algorithm.
    Example:

    echo password_hash("mypassword", PASSWORD_DEFAULT);
    // Output: $2y$10$...

    echo()

    Description: Outputs one or more strings.
    Example:

    echo "Hello", " World!";
    // Output: Hello World!

    explode()

    Description: Splits a string by a specified delimiter into an array.
    Example:

    print_r(explode(" ", "Hello World"));
    // Output: Array ( [0] => Hello [1] => World )

    hex2bin()

    Description: Converts a hexadecimal string to binary.
    Example:

    echo hex2bin("48656c6c6f");
    // Output: Hello

    implode()

    Description: Joins array elements into a single string.
    Example:

    echo implode(", ", array("apple", "banana", "cherry"));
    // Output: apple, banana, cherry

    lcfirst()

    Description: Converts the first character of a string to lowercase.
    Example:

    echo lcfirst("HELLO");
    // Output: hELLO

    levenshtein()

    Description: Returns the Levenshtein distance between two strings.
    Example:

    echo levenshtein("kitten", "sitting");
    // Output: 3

    ltrim()

    Description: Strips whitespace from the beginning of a string.
    Example:

    echo ltrim("    Hello");
    // Output: Hello

    md5_file()

    Description: Generates the MD5 hash of a file.
    Example:

    echo md5_file("example.txt");
    // Output: 5d41402abc4b2a76b9719d911017c592

    md5()

    Description: Generates the MD5 hash of a string.
    Example:

    echo md5("Hello World");
    // Output: b10a8db164e0754105b7a99be72e3fe5

    metaphone()

    Description: Computes the metaphone key of a string for phonetic comparisons.
    Example:

    echo metaphone("example");
    // Output: EXMPL

    nl2br()

    Description: Inserts HTML line breaks before newlines in a string.
    Example:

    echo nl2br("Hello\nWorld!");
    // Output: Hello<br />World!
  • PHP Array Functions

    PHP Array Functions

    array_chunk()

    Description:Splits an array into chunks of a specified size.

    Example:

    $array = array(1, 2, 3, 4, 5, 6);
    print_r(array_chunk($array, 2));
    // Output:
    // Array
    // (
    //     [0] => Array ( [0] => 1 [1] => 2 )
    //     [1] => Array ( [0] => 3 [1] => 4 )
    //     [2] => Array ( [0] => 5 [1] => 6 )
    // )

    array_combine()

    Description:Creates an array by combining one array as keys and another array as values.

    Example:

    $keys = array('fruit', 'vegetable');
    $values = array('apple', 'carrot');
    print_r(array_combine($keys, $values));
    // Output:
    // Array
    // (
    //     [fruit] => apple
    //     [vegetable] => carrot
    // )

    array_count_values()

    Description:Counts the occurrences of all values in an array.

    Example:

    $array = array(1, "hello", 1, "world", "hello");
    print_r(array_count_values($array));
    // Output:
    // Array
    // (
    //     [1] => 2
    //     [hello] => 2
    //     [world] => 1
    // )

    array_diff()

    Description:Computes the difference between two or more arrays.

    Example:

    $array1 = array("a" => "green", "b" => "brown", "c" => "blue");
    $array2 = array("a" => "green", "yellow", "red");
    print_r(array_diff($array1, $array2));
    // Output:
    // Array
    // (
    //     [b] => brown
    //     [c] => blue
    // )

    array_fill()

    Description:Fills an array with a specified value, starting from a specified index.

    Example:

    print_r(array_fill(3, 5, "apple"));
    // Output:
    // Array
    // (
    //     [3] => apple
    //     [4] => apple
    //     [5] => apple
    //     [6] => apple
    //     [7] => apple
    // )

    array_filter()

    Description:Filters elements of an array using a callback function.

    Example:

    $array = array(1, 2, 3, 4, 5, 6);
    print_r(array_filter($array, function($value) { return $value % 2 == 0; }));
    // Output:
    // Array
    // (
    //     [1] => 2
    //     [3] => 4
    //     [5] => 6
    // )

    array_flip()

    Description:Exchanges keys and values in an array.

    Example:

    $array = array("a" => "apple", "b" => "banana", "c" => "cherry");
    print_r(array_flip($array));
    // Output:
    // Array
    // (
    //     [apple] => a
    //     [banana] => b
    //     [cherry] => c
    // )

    array_key_exists()

    Description:Checks if a specified key exists within an array.

    Example:

    $array = array("fruit" => "apple", "vegetable" => "carrot");
    echo array_key_exists("fruit", $array) ? "Key exists" : "Key does not exist";
    // Output: Key exists

    array_merge()

    Description:Merges one or more arrays into a single array.

    Example:

    $array1 = array("color" => "red", 2, 4);
    $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
    print_r(array_merge($array1, $array2));
    // Output:
    // Array
    // (
    //     [color] => green
    //     [0] => 2
    //     [1] => 4
    //     [2] => a
    //     [3] => b
    //     [shape] => trapezoid
    //     [4] => 4
    // )

    array_reverse()

    Description:Reverses the order of elements in an array.

    Example:

    $array = array("a", "b", "c", "d");
    print_r(array_reverse($array));
    // Output:
    // Array
    // (
    //     [0] => d
    //     [1] => c
    //     [2] => b
    //     [3] => a
    // )

    array_search()

    Description:Searches for a value in an array and returns the corresponding key if found.

    Example:

    $array = array(0 => 'blue', 1 => 'red', 2 => 'green');
    echo array_search('green', $array);
    // Output: 2

    array_sum()

    Description:Returns the sum of all values in an array.

    Example:

    $array = array(2, 4, 6, 8);
    echo array_sum($array);
    // Output: 20

    array_unique()

    Description:Removes duplicate values from an array.

    Example:

    $array = array("apple", "banana", "apple", "orange");
    print_r(array_unique($array));
    // Output:
    // Array
    // (
    //     [0] => apple
    //     [1] => banana
    //     [3] => orange
    // )

    array_values()

    Description:Returns all the values from an array, with numeric keys starting from 0.

    Example:

    $array = array("size" => "large", "color" => "red");
    print_r(array_values($array));
    // Output:
    // Array
    // (
    //     [0] => large
    //     [1] => red
    // )

    compact()

    Description:Create an array using variables as keys and their values as elements.

    Example:

    $name = "John";
    $age = 30;
    print_r(compact("name", "age"));
    // Output: Array ( [name] => John [age] => 30 )

    count()

    Description:Count the total number of elements in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo count($array);
    // Output: 3

    current()

    Description:Return the value of the element at the internal pointer in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo current($array);
    // Output: apple

    end()

    Description:Find the last element of a given array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo end($array);
    // Output: cherry

    extract()

    Description:Convert array elements into variables.

    Example:

    $array = array("name" => "John", "age" => 30);
    extract($array);
    echo $name;
    // Output: John

    in_array()

    Description:Check if a specific value exists in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo in_array("banana", $array) ? "Found" : "Not found";
    // Output: Found

    key()

    Description:Return the current index or key of an array where the internal pointer points.

    Example:

    $array = array("a" => "apple", "b" => "banana");
    echo key($array);
    // Output: a

    krsort()

    Description:Sort an array by its keys in descending order.

    Example:

    $array = array("a" => "apple", "c" => "cherry", "b" => "banana");
    krsort($array);
    print_r($array);
    // Output: Array ( [c] => cherry [b] => banana [a] => apple )

    list()

    Description:Assign array values to multiple variables.

    Example:

    $array = array("apple", "banana", "cherry");
    list($fruit1, $fruit2) = $array;
    echo $fruit1;
    // Output: apple

    natcasesort()

    Description:Sort an array using natural order, case-insensitively.

    Example:

    $array = array("Image2.jpg", "image10.jpg", "Image1.jpg");
    natcasesort($array);
    print_r($array);
    // Output: Array ( [0] => Image1.jpg [2] => Image2.jpg [1] => image10.jpg )

    natsort()

    Description:Sort an array using a “natural order” algorithm without regard to case.

    Example:

    $array = array("Image2.jpg", "image10.jpg", "Image1.jpg");
    natsort($array);
    print_r($array);
    // Output: Array ( [2] => Image1.jpg [0] => Image2.jpg [1] => image10.jpg )

    next()

    Description:Move the internal pointer to the next element and return its value.

    Example:

    $array = array("apple", "banana", "cherry");
    echo next($array);
    // Output: banana

    pos()

    Description:Return the value of the current element of an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo pos($array);
    // Output: apple

    prev()

    Description:Move the internal pointer to the previous element and return its value.

    Example:

    $array = array("apple", "banana", "cherry");
    next($array);
    echo prev($array);
    // Output: apple

    range()

    Description:Create an array with elements within a specified range.

    Example:

    print_r(range(0, 5));
    // Output: Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 )

    reset()

    Description:Move the internal pointer to the first element of an array.

    Example:

    $array = array("apple", "banana", "cherry");
    echo reset($array);
    // Output: apple

    rsort()

    Description:Sort an array in descending order.

    Example:

    $array = array(3, 1, 2);
    rsort($array);
    print_r($array);
    // Output: Array ( [0] => 3 [1] => 2 [2] => 1 )

    shuffle()

    Description:Randomize the order of elements in an array.

    Example:

    $array = array("apple", "banana", "cherry");
    shuffle($array);
    print_r($array);
    // Output: (random order, e.g., Array ( [0] => banana [1] => cherry [2] => apple ))

    sizeof()

    Description:Count the number of elements in an array or countable object.

    Example:

    $array = array("apple", "banana", "cherry");
    echo sizeof($array);
    // Output: 3

    sort()

    Description:Sort an array in ascending order.

    Example:

    $array = array(3, 1, 2);
    sort($array);
    print_r($array);
    // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )

    uasort()

    Description:Sort an array while maintaining index association, using a user-defined function.

    Example:

    $array = array("a" => 3, "b" => 1, "c" => 2);
    uasort($array, function($x, $y) { return $x <=> $y; });
    print_r($array);
    // Output: Array ( [b] => 1 [c] => 2 [a] => 3 )

    usort()

    Description:Sort an array using a custom comparison function.

    Example:

    $array = array("apple", "banana", "cherry");
    usort($array, function($x, $y) { return strlen($x) <=> strlen($y); });
    print_r($array);
    // Output: Array ( [0] => apple [1] => cherry [2] => banana )
  • MySQL Database

    PHP MySQL Database Introduction

    What is MySQL?

    MySQL is an open-source relational database management system (RDBMS) widely used in conjunction with PHP. It is currently one of the most popular database systems and is developed, distributed, and maintained by Oracle Corporation.

    • Data within a MySQL database is organized into tables consisting of rows and columns.
    • MySQL operates as a server-based database system.
    • It is well-suited for both small and large-scale applications.
    • Known for its speed, reliability, and ease of use, MySQL uses standard SQL (Structured Query Language).
    • MySQL can run on various platforms.
    Downloading MySQL Database

    You can download MySQL for free from the official MySQL website.

    How to Connect PHP to a MySQL Database?

    In PHP version 5 and above, MySQL can be accessed using two primary methods:

    • MySQLi extension.
    • PDO (PHP Data Objects).
    Difference Between MySQLi and PDO
    • PDO supports 12 different types of databases, while MySQLi is exclusively for MySQL databases.
    • Both PDO and MySQLi offer object-oriented interfaces, but MySQLi also provides a procedural interface.
    • If you need to switch your project from MySQL to another database system, PDO allows this with minimal changes to the connection string and a few queries. With MySQLi, you would have to rewrite the entire codebase, including all queries.
    Ways to Work with MySQL in PHP

    There are three primary methods to connect and interact with a MySQL database in PHP:

    1. MySQLi (Object-Oriented)
    2. MySQLi (Procedural)
    3. PDO (PHP Data Objects)

    Connecting to a MySQL Database using PHP

    Below are the three different approaches to connect to a MySQL database from a PHP script.

    1. MySQLi Object-Oriented Approach: You can use the object-oriented approach with MySQLi to create a connection to the MySQL database.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    ?>

    Output:

    Connected successfully

    2. MySQLi Procedural Approach: You can also establish a connection using MySQLi’s procedural interface.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Create connection
    $conn = mysqli_connect($servername, $username, $password);
    
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
    ?>

    Output:

    Connected successfully

    3. PDO Approach: PDO offers a unified interface for connecting to a MySQL database and can be easily adapted for other database systems.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
        // Set PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    }
    catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    ?>

    Output:

    Connected successfully

    PHP MySQL ( Creating Database )

    What is a Database?

    A database is a structured collection of related data that allows efficient storage, retrieval, insertion, and deletion of information. It organizes data into tables, views, schemas, reports, etc., facilitating streamlined data management. For instance, a university database may organize data about students, faculty, and administration, which enables effective data operations such as retrieval and insertion.

    To create a database in MySQL, a SQL query is needed. Here are the steps to create a MySQL database using PHP:

    1. Establish a connection to the MySQL server from the PHP script.
    2. If the connection is successful, write a SQL query to create a database and store it in a string variable.
    3. Execute the query.

    We already know how to establish a connection and create variables in PHP. The query can be executed in three different ways, as shown below:

    1. Using MySQLi Object-Oriented Approach: If the MySQL connection is made using the object-oriented approach, the query() method of the mysqli class is used to run the query.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Establishing connection
    $conn = new mysqli($servername, $username, $password);
    
    // Checking connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL query to create a database named newDB
    $sql = "CREATE DATABASE newDB";
    if ($conn->query($sql) === TRUE) {
        echo "Database created successfully with the name newDB";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    
    // Closing connection
    $conn->close();
    ?>

    Output:

    Database created successfully with the name newDB

    2. Using MySQLi Procedural Approach: If the MySQL connection is established using the procedural approach, the mysqli_query() function is used to execute the query.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    // Establishing connection
    $conn = mysqli_connect($servername, $username, $password);
    
    // Checking connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    // SQL query to create a database named newDB
    $sql = "CREATE DATABASE newDB";
    if (mysqli_query($conn, $sql)) {
        echo "Database created successfully with the name newDB";
    } else {
        echo "Error creating database: " . mysqli_error($conn);
    }
    
    // Closing connection
    mysqli_close($conn);
    ?>

    Output:

    Database created successfully with the name newDB

    3. Using PDO Approach: If the connection is made using PDO, the query can be executed as shown below.

    Syntax:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=newDB", $username, $password);
        // Setting PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // SQL query to create a database named newDB
        $sql = "CREATE DATABASE newDB";
    
        // Executing the query using exec() as no results are returned
        $conn->exec($sql);
        echo "Database created successfully with the name newDB";
    }
    catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }
    
    // Closing the connection
    $conn = null;
    ?>

    Output:

    Database created successfully with the name newDB

    PHP Database connection

    The collection of related data is called a database.

    XAMPP is an abbreviation for Cross-Platform, Apache, MySQL, PHP, and Perl. It is a lightweight and straightforward local server used for website development.

    Requirements:

    Procedure to use the XAMPP web server:

    1. Start the XAMPP server by running Apache and MySQL.
    2. Write a PHP script for connecting to the XAMPP server.
    3. Run the script in your local browser.
    4. A database is created based on the PHP code.

    In PHP, we can connect to a database using the XAMPP server by navigating to the following path:

    “localhost/phpmyadmin”

    Steps in Detail:

    1. Open XAMPP and start the Apache, MySQL, and FileZilla services.
    2. Now open your PHP file and write the PHP code to create a database and a table.

    PHP Code to Create a Database:

    <?php
    
    // Server name is typically localhost
    $servername = "localhost";
    
    // Username for XAMPP is generally root
    $username = "root";
    
    // No password by default in XAMPP
    $password = "";
    
    // Establishing a connection
    $conn = new mysqli($servername, $username, $password);
    
    // Checking the connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL to create a database named myDB
    $sql = "CREATE DATABASE myDB";
    if ($conn->query($sql) === TRUE) {
        echo "Database 'myDB' created successfully";
    } else {
        echo "Error creating database: " . $conn->error;
    }
    
    // Closing the connection
    $conn->close();
    ?>

    Steps to Follow:

    • Save the file as “create_database.php” in the htdocs folder located in your XAMPP installation directory.
    • Open your web browser and navigate to localhost/create_database.php.

    Final Step:

    • The database will be created and connected to PHP.
    • To view your newly created database, type localhost/phpmyadmin in your web browser, and the database will appear.

    Output:

    Database 'myDB' created successfully

    Connect PHP to MySQL

    MySQL can run on a server and is well-suited for both small and large applications. It is known for being fast, reliable, and easy to use. Additionally, it supports SQL standards and is available on multiple platforms.

    How to Connect PHP with MySQL?

    Starting with PHP 5, there are two main ways to interact with MySQL databases:

    • MySQLi extension (where “i” stands for “improved”)
    • PDO (PHP Data Objects)
    Should You Use MySQLi or PDO?

    Both MySQLi and PDO have their advantages:

    • PDO works with 12 different types of databases, whereas MySQLi is specifically designed to work only with MySQL databases.
    • If you foresee switching to another database system, PDO simplifies the transition by only requiring changes to the connection string and some queries. With MySQLi, you would need to rewrite the entire codebase, including queries.
    • Both provide object-oriented interfaces, though MySQLi also offers a procedural API.

    In short, if you are only using MySQL, both are good options, but if you may switch databases, PDO is more flexible.

    Connecting PHP to MySQL

    Using MySQLi (Object-Oriented): Here is how you can establish a connection to a MySQL database using MySQLi in object-oriented style:

    <?php
    $server = "localhost";
    $user = "admin";
    $pass = "admin123";
    
    // Establishing the connection
    $connection = new mysqli($server, $user, $pass);
    
    // Check the connection
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }
    
    echo "Connection successful!";
    ?>

    Output:

    Connection successful!

    Using MySQLi (Procedural): The procedural approach to connect PHP with MySQL using MySQLi looks like this:

    <?php
    $server = "localhost";
    $user = "admin";
    $pass = "admin123";
    
    // Establishing the connection
    $connection = mysqli_connect($server, $user, $pass);
    
    // Checking the connection
    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    echo "Connection successful!";
    ?>

    Output:

    Connection successful!

    PHP MySQL ( Creating Table )

    What is a Table?

    In relational and flat file databases, a table refers to an organized structure where data elements are stored in the form of vertical columns and horizontal rows. Each row represents a data record, and each column represents a specific field. A table has a fixed number of columns but can have an unlimited number of rows. The point where a row and column meet is known as a cell.

    Creating a MySQL Table Using MySQLi and PDO

    The process of creating a table is similar to creating a database. However, instead of creating a new database, you will connect to an existing database and define a table within it. To connect to an existing database, you need to specify the database name during the connection to MySQL.

    The CREATE TABLE statement is used to define a new table.

    In the following example, we will create a table named “customers” with four columns: customer_idfirst_namelast_name, and email.

    The data types used are:

    • VARCHAR: Holds a string of variable length, containing letters, numbers, and special characters. The maximum size is defined in parentheses.
    • INT: Holds integer values, ranging between -2147483648 to 2147483647.

    Attributes used:

    • NOT NULL: Ensures that every row must have a value in the column.
    • PRIMARY KEY: Uniquely identifies each row in the table. Often applied to an ID column.

    Creating a Table Using MySQLi Object-Oriented Procedure

    <?php
    $server = "localhost";
    $user = "root";
    $pass = "";
    $dbname = "shopDB";
    
    // Establishing connection
    $conn = new mysqli($server, $user, $pass, $dbname);
    
    // Checking the connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL code to create the table
    $sql = "CREATE TABLE customers (
            customer_id INT(3) PRIMARY KEY,
            first_name VARCHAR(40) NOT NULL,
            last_name VARCHAR(40) NOT NULL,
            email VARCHAR(60)
            )";
    
    if ($conn->query($sql) === TRUE) {
        echo "Table customers created successfully";
    } else {
        echo "Error creating table: " . $conn->error;
    }
    
    // Closing connection
    $conn->close();
    ?>

    Creating a Table Using MySQLi Procedural Procedure

    <?php
    $server = "localhost";
    $user = "root";
    $pass = "";
    $dbname = "shopDB";
    
    // Establishing connection
    $conn = mysqli_connect($server, $user, $pass, $dbname);
    
    // Checking connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    // SQL code to create the table
    $sql = "CREATE TABLE customers (
            customer_id INT(3) PRIMARY KEY,
            first_name VARCHAR(40) NOT NULL,
            last_name VARCHAR(40) NOT NULL,
            email VARCHAR(60)
            )";
    
    if (mysqli_query($conn, $sql)) {
        echo "Table customers created successfully";
    } else {
        echo "Error creating table: " . mysqli_error($conn);
    }
    
    // Closing connection
    mysqli_close($conn);
    ?>

    Output:

    Table customers created successfully

    Creating a Table Using PDO

    <?php
    $server = "localhost";
    $user = "root";
    $pass = "";
    $dbname = "shopDB";
    
    try {
        // Establishing connection
        $conn = new PDO("mysql:host=$server;dbname=$dbname", $user, $pass);
    
        // Setting PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // SQL code to create the table
        $sql = "CREATE TABLE customers (
                customer_id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                first_name VARCHAR(40) NOT NULL,
                last_name VARCHAR(40) NOT NULL,
                email VARCHAR(60)
                )";
    
        // Using exec() as no results are returned
        $conn->exec($sql);
        echo "Table customers created successfully";
    }
    catch(PDOException $e) {
        echo $sql . "<br>" . $e->getMessage();
    }
    
    // Closing connection
    $conn = null;
    ?>

    Output:

    Table customers created successfully

    PHP Inserting into MySQL database

    Inserting Data into a MySQL Database Using PHP

    Inserting data into a MySQL database using PHP is a key task in many web applications. This allows developers to dynamically manage and store data, such as user inputs, for a wide variety of tasks like content management, e-commerce, and more.

    In this section, we’ll explore how to insert records into a MySQL database using PHP. The process involves creating a connection to the database, writing an SQL INSERT statement, executing it, and handling any potential errors.

    Inserting Data Using MySQLi (Object-Oriented Approach)

    Let’s assume we are inserting a new record into a MySQL table named people. The objective is to add the namesurname, and age of an individual.

    <?php
    $mysqli = new mysqli("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    // Insert data
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('John', 'Doe', '30')";
    
    if ($mysqli->query($sql) === true) {
        echo "Record inserted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    // Close connection
    $mysqli->close();
    ?>

    Output:

    Record inserted successfully.
    Inserting Data Using MySQLi (Procedural Approach)

    In this case, we are inserting data into the people table using the MySQLi procedural method. The values to be added are AnnaSmith, and 24 for name, surname, and age, respectively.

    <?php
    $link = mysqli_connect("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    // Insert data
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('Anna', 'Smith', '24')";
    
    if (mysqli_query($link, $sql)) {
        echo "Record added successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    // Close connection
    mysqli_close($link);
    ?>

    Output:

    Record added successfully.
    Inserting Data Using PDO

    In this example, we are inserting data into the people table using the PDO method. The script will handle any errors that might occur during the connection or execution phases.

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "admin", "password123");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        // Insert data
        $sql = "INSERT INTO people (name, surname, age)
                VALUES ('David', 'Lee', '28')";
        $pdo->exec($sql);
        echo "Record inserted successfully.";
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    // Close connection
    unset($pdo);
    ?>

    Output:

    Record inserted successfully.
    Inserting Multiple Rows into a Table

    You can also insert multiple rows into a table with a single INSERT query. To do this, add multiple sets of values within the query, where each set is enclosed in parentheses and separated by commas.

    Inserting Multiple Rows Using MySQLi (Object-Oriented Approach)

    <?php
    $mysqli = new mysqli("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    // Insert multiple rows
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('Alice', 'Brown', '22'),
                   ('Tom', 'Harris', '35'),
                   ('Emily', 'Clark', '27'),
                   ('Luke', 'Morris', '31')";
    
    if ($mysqli->query($sql) === true) {
        echo "Records inserted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    // Close connection
    $mysqli->close();
    ?>

    Output:

    Records inserted successfully.

    Inserting Multiple Rows Using MySQLi (Procedural Approach)

    <?php
    $link = mysqli_connect("localhost", "admin", "password123", "mydatabase");
    
    // Check connection
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    // Insert multiple rows
    $sql = "INSERT INTO people (name, surname, age)
            VALUES ('Michael', 'Smith', '40'),
                   ('Nina', 'Johnson', '29'),
                   ('Chris', 'Evans', '33'),
                   ('Sophia', 'Martinez', '24')";
    
    if (mysqli_query($link, $sql)) {
        echo "Records added successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    // Close connection
    mysqli_close($link);
    ?>

    Output:

    Records added successfully.

    Inserting Multiple Rows Using PDO

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "admin", "password123");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        // Insert multiple rows
        $sql = "INSERT INTO people (name, surname, age)
                VALUES ('Olivia', 'Taylor', '21'),
                       ('James', 'Wilson', '37'),
                       ('Isabella', 'Garcia', '30'),
                       ('Liam', 'White', '45')";
        $pdo->exec($sql);
        echo "Records inserted successfully.";
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    // Close connection
    unset($pdo);
    ?>

    Output:

    Records inserted successfully.

    PHP MySQL Delete Query

    The DELETE query is used to remove records from a table in a database. It is often used with a SELECT statement to delete only those rows that meet a certain condition.

    Syntax:

    The basic syntax for a DELETE query is as follows:

    Example Implementation:

    Let us consider a table called Employees with four columns: EmployeeIDFirstNameLastName, and Position. Below are examples of how to delete the record of an employee whose EmployeeID is 101 from the Employees table using different MySQLi and PDO methods.

    1. DELETE Query Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "CompanyDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "DELETE FROM Employees WHERE EmployeeID = 101";
    if (mysqli_query($link, $sql)) {
        echo "Record deleted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code will delete the record where the EmployeeID is 101 from the Employees table. After execution, a confirmation message will be displayed: “Record deleted successfully.”

    2. SELECT Query Using MySQLi Object-Oriented Method:

    <?php
    $mysqli = new mysqli("localhost", "root", "", "SampleDB");
    
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    $sql = "SELECT * FROM Users";
    if ($res = $mysqli->query($sql)) {
        if ($res->num_rows > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = $res->fetch_array()) {
                echo "<tr>";
                echo "<td>".$row['FirstName']."</td>";
                echo "<td>".$row['LastName']."</td>";
                echo "<td>".$row['Age']."</td>";
                echo "</tr>";
            }
            echo "</table>";
            $res->free();
        } else {
            echo "No records found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    $mysqli->close();
    ?>

    Output:

    Similar to the previous example, this code will output the data in an HTML table format. If there are no matching records, it will show “No records found.”

    PHP MySQL WHERE Clause

    The WHERE clause is used to filter records based on a specific condition provided by the user. Essentially, it helps restrict the number of rows returned or affected by a SELECTUPDATE, or DELETE query.

    Syntax:

    The basic syntax for using the WHERE clause is as follows:

    SELECT Column1, Column2, ...
    FROM Table_Name
    WHERE Condition;

    Example of WHERE Clause:

    Let’s consider a table called Students with three columns: FirstNameLastName, and Age.

    To retrieve all the rows where the FirstName is “John”, we will use the following code examples:

    1. WHERE Clause Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "SchoolDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "SELECT * FROM Students WHERE FirstName='John'";
    if ($res = mysqli_query($link, $sql)) {
        if (mysqli_num_rows($res) > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = mysqli_fetch_array($res)) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            mysqli_free_result($res);
        } else {
            echo "No matching records found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code fetches all records from the Students table where the FirstName is “John.” The matching rows are displayed in a table format.

    2. WHERE Clause Using MySQLi Object-Oriented Method:

    <?php
    $mysqli = new mysqli("localhost", "root", "", "SchoolDB");
    
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    $sql = "SELECT * FROM Students WHERE FirstName='John'";
    if ($res = $mysqli->query($sql)) {
        if ($res->num_rows > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = $res->fetch_array()) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            $res->free();
        } else {
            echo "No matching records found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    $mysqli->close();
    ?>

    Output:

    In this example, the object-oriented method retrieves all the rows from the Students table where the FirstName is “John” and displays them in a table format.

    3. WHERE Clause Using PDO Method:

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=SchoolDB", "root", "");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        $sql = "SELECT * FROM Students WHERE FirstName='John'";
        $res = $pdo->query($sql);
        if ($res->rowCount() > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = $res->fetch()) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            unset($res);
        } else {
            echo "No matching records found.";
        }
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    unset($pdo);
    ?>

    Output:

    The PDO example runs a query to select all rows from the Students table where the FirstName is “John.” The results are displayed in a table format.

    PHP MySQL UPDATE Query

    The MySQL UPDATE query is utilized to modify existing records in a table within a MySQL database.

    It allows updating one or more fields simultaneously and can be used in conjunction with the WHERE clause to specify conditions for the update.

    Syntax:

    The basic syntax for the UPDATE query is as follows:

    UPDATE table_name
    SET column1 = value1, column2 = value2, ...
    WHERE condition;

    Example of WHERE Update Query:

    Let’s consider a table called Employees with columns IDFirstNameLastName, and Age.

    To update the Age of an employee with ID 105 in the Employees table, we can use the following code:

    1. Update Query Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "CompanyDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "UPDATE Employees SET Age='32' WHERE ID=105";
    if (mysqli_query($link, $sql)) {
        echo "Record was updated successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code updates the Age of the employee with ID 105 to 32. If successful, a message is displayed indicating the update.

    2. Update Query Using MySQLi Object-Oriented Method:

    <?php
    $mysqli = new mysqli("localhost", "root", "", "CompanyDB");
    
    if ($mysqli === false) {
        die("ERROR: Could not connect. " . $mysqli->connect_error);
    }
    
    $sql = "UPDATE Employees SET Age='32' WHERE ID=105";
    if ($mysqli->query($sql) === true) {
        echo "Record was updated successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . $mysqli->error;
    }
    
    $mysqli->close();
    ?>

    Output:

    In this example, the Age of the employee with ID 105 is updated to 32. A success message is shown if the query is executed without errors.

    3. Update Query Using PDO Method:

    <?php
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=CompanyDB", "root", "");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("ERROR: Could not connect. " . $e->getMessage());
    }
    
    try {
        $sql = "UPDATE Employees SET Age='32' WHERE ID=105";
        $pdo->exec($sql);
        echo "Record was updated successfully.";
    } catch (PDOException $e) {
        die("ERROR: Could not execute $sql. " . $e->getMessage());
    }
    
    unset($pdo);
    ?>

    Output:

    This PDO method updates the Age of the employee with ID 105 to 32, and a confirmation message is displayed upon successful execution.

    PHP MySQL LIMIT Clause

    In MySQL, the LIMIT clause is used in conjunction with the SELECT statement to control the number of rows returned in the result set. The LIMIT clause accepts either one or two arguments: offset and count. Both values must be non-negative integers.

    • Offset: This specifies the position of the first row to return.
    • Count: This defines the maximum number of rows to return.

    When two parameters are used, the first one represents the offset and the second indicates the count. If only one parameter is provided, it represents the number of rows to return from the start of the result set.

    Syntax:

    SELECT column1, column2, ...
    FROM table_name
    LIMIT offset, count;

    Example:

    Let’s consider the following table named Employees, which contains three columns: FirstNameLastName, and Age.

    To retrieve the first two rows from the Employees table, use the following query:

    SELECT * FROM Employees LIMIT 2;

    To fetch rows starting from the second row and retrieve two rows (rows 2 and 3 inclusive), use the following query:

    SELECT * FROM Employees LIMIT 1, 2;

    Below is the PHP implementation of the query to display the first two rows from the Employees table using the LIMIT clause in both procedural and object-oriented methods:

    1. Limit Clause Using MySQLi Procedural Method:

    <?php
    $link = mysqli_connect("localhost", "root", "", "CompanyDB");
    
    if ($link === false) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
    $sql = "SELECT * FROM Employees LIMIT 2";
    if ($res = mysqli_query($link, $sql)) {
        if (mysqli_num_rows($res) > 0) {
            echo "<table>";
            echo "<tr>";
            echo "<th>FirstName</th>";
            echo "<th>LastName</th>";
            echo "<th>Age</th>";
            echo "</tr>";
            while ($row = mysqli_fetch_array($res)) {
                echo "<tr>";
                echo "<td>" . $row['FirstName'] . "</td>";
                echo "<td>" . $row['LastName'] . "</td>";
                echo "<td>" . $row['Age'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            mysqli_free_result($res);
        } else {
            echo "No matching records were found.";
        }
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }
    
    mysqli_close($link);
    ?>

    Output:

    This code retrieves and displays the first two rows from the Employees table, showing FirstNameLastName, and Age fields.