Current Location: Home> Latest Articles> Example of using wrong font number to raise imagefontwidth() error

Example of using wrong font number to raise imagefontwidth() error

M66 2025-05-24

In PHP, the imagefontwidth() function is used to get the character width of the specified built-in font. The syntax of this function is as follows:

 int imagefontwidth(int $font)

The parameter $font is an integer representing the font number. The built-in font number of PHP is usually between 1 and 5. If a font number that does not exist or is invalid is passed, the imagefontwidth() function will report an error.

Why is there an error?

imagefontwidth() relies on built-in font resources, and the font sizes and styles corresponding to these font numbers are predefined. If a number that is not within the valid range is passed in, the function cannot find the corresponding font data, and naturally cannot return the width information, resulting in an error.

Give a specific example

The following code demonstrates how to incorrectly use font numbering to cause an error in imagefontwidth() .

 <?php
// Incorrect font number,For example7(The effective range is1-5)
$font = 7;

try {
    // Try to get the character width of the font
    $width = imagefontwidth($font);
    echo "Font number $font The character width is: $width";
} catch (Error $e) {
    echo "mistake: " . $e->getMessage();
}
?>

Running the above code will cause an error message similar to the following:

 Warning: imagefontwidth(): supplied font is not valid

This is because the font number 7 does not exist, causing the function call to fail.

Correct usage

To avoid this error, when using imagefontwidth() , you should make sure that the font number is between 1 and 5, as follows:

 <?php
$font = 3;  // 正确的Font number

$width = imagefontwidth($font);
echo "Font number $font The character width is: $width";
?>

This code will correctly output the character width corresponding to font number 3.

Summarize

  • The parameter of imagefontwidth() must be an integer between 1 and 5, indicating the built-in font.

  • Passing in invalid font numbers will cause the function to report an error.

  • During development, you should pay attention to checking the effectiveness of font numbers and avoid using non-existent font numbers.

This simple example can help you better understand the usage specifications of the imagefontwidth() function and avoid program errors due to font number errors.