How can one compare the first few characters of two variables in PHP?

To compare the first few characters of two variables in PHP, you can use the substr() function to extract the desired number of characters from each variable and then compare them using the strcmp() function. This allows you to check if the first few characters of both variables are equal or not.

$var1 = "example1";
$var2 = "example2";

$first_chars_var1 = substr($var1, 0, 3); // Extract first 3 characters of $var1
$first_chars_var2 = substr($var2, 0, 3); // Extract first 3 characters of $var2

if (strcmp($first_chars_var1, $first_chars_var2) === 0) {
    echo "The first few characters of both variables are equal.";
} else {
    echo "The first few characters of both variables are not equal.";
}