HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Find the inverted value of the string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theinvertedvaluefindstring

Problem

How can this be optimized?

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

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

echo ($b) ? "YES" : "NO"; // result: NO.

Solution

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  %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) -> YES
isPalindrome(hello) -> NO
isPalindrome(aba) -> YES
isPalindrome(aa) -> YES
isPalindrome(ab) -> NO

Code Snippets

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

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

test_isPalindrome("reverseesrever");
test_isPalindrome("hello");
test_isPalindrome("aba");
test_isPalindrome("aa");
test_isPalindrome("ab");
isPalindrome(reverseesrever) -> YES
isPalindrome(hello) -> NO
isPalindrome(aba) -> YES
isPalindrome(aa) -> YES
isPalindrome(ab) -> NO

Context

StackExchange Code Review Q#48671, answer score: 4

Revisions (0)

No revisions yet.