Find the inverted value of the string How can this be optimized?

$text = "reverseesrever"; // Reverse and esrever
$b = false;

for($i = 0; $i &lt; strlen($text); $i++) {
    if($text[$i] !== $text[strlen($text) - 1 - $i]) {
        $b = true;
        break;
    }
}

echo ($b) ? "YES" : "NO"; // result: NO.
The title of the question is confusing. The code seem to check if the text is not the same if you read it backward. For example, it $b will be true for "hello" and false for "level". In other words, you're checking if some text is NOT a palindrome. I think you should change the title to better reflect what the code is doing.

Things to improve:


It's enough to iterate until strlen($text) / 2, no need to go all the way until the end
To avoid re-calculating the length of the string, it's better to calculate it once before the loop and reuse it
Wrap the whole thing in a function to make it easier to reuse and to test
The !== is unnecessary, a simple != would do


For example:

function isPalindrome($text) {
    $length = strlen($text);
    for ($i = 0; $i &lt; $length / 2; $i++) {
        if ($text[$i] != $text[$length - 1 - $i]) {
            return false;
        }
    }
    return true;
}

function test_isPalindrome($text) {
    printf("isPalindrome(%s) -&gt; %s\n", $text, isPalindrome($text) ? 'YES' : 'NO');
}

test_isPalindrome("reverseesrever");
test_isPalindrome("hello");
test_isPalindrome("aba");
test_isPalindrome("aa");
test_isPalindrome("ab");


Outputs:

isPalindrome(reverseesrever) -&gt; YES
isPalindrome(hello) -&gt; NO
isPalindrome(aba) -&gt; YES
isPalindrome(aa) -&gt; YES
isPalindrome(ab) -&gt; NO