Skip to content
PHP Logo

How can the width of text be calculated in pixels in PHP?

To calculate the width of text in pixels in PHP, you can use the `imagettfbbox()` function from the GD library. This function calculates the bounding box of a text using a TrueType font and returns an array containing the coordinates of the box. By subtracting the x-coordinate of the starting point from the x-coordinate of the ending point, you can determine the width of the text in pixels.

php
$text = "Hello, World!";
$font_size = 12;
$font_path = "path/to/font.ttf";

$bbox = imagettfbbox($font_size, 0, $font_path, $text);
$text_width = $bbox[2] - $bbox[0];

echo "The width of the text is: " . $text_width . " pixels";