PHP Failed asserting that two strings are equal

I’m on training test in codewars.com,

The instruction is :

  • In this kata you are required to, given a string, replace every letter with its position in the alphabet.
  • If anything in the text isn’t a letter, ignore it and don’t return it. “a” = 1, “b” = 2.

And i already make PHP script like this

<?php
function alphabet_position($string) 
{
    $lower = strtolower($string);
    $alphabet = range("a", "z");
    $result = "";

    for ($i=0; $i<strlen($lower); $i++)
    {
      $filter = array_search($lower[$i], $alphabet);
      if ($filter)
        {
          $result .= $filter+1 ." ";
        }
    }
    
    return $result;
}

echo alphabet_position('The sunset sets at twelve o'clock');
//output 20 8 5 19 21 14 19 5 20 19 5 20 19 20 20 23 5 12 22 5 15 3 12 15 3 11

but when i submit my answer, its contain error like

Time: 937msPassed: 0Failed: 1Exit Code: 1
Test Results:
Log
PHPUnit 9.1.1 by Sebastian Bergmann and contributors.
AlphabetPositionTest
testFixed
Failed asserting that two strings are equal.
Expected: '20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
Actual  : ''
Completed in 23.3161ms

Please anyone can help fix it? and tell me the detail why its showing error?

Answer

If a character is a, array_search() would return 0 and if($filter) would ignore it as if(0) is false. Hence, you use strict type check to avoid the issue.

<?php
function alphabet_position($string) {
    $lower = strtolower($string);
    $alphabet = range("a", "z");
    $parts = [];

    for ($i=0; $i < strlen($lower); $i++)
    {
        $filter = array_search($lower[$i], $alphabet);
        if ($filter !== false){ // always have strict type check as array index can also be 0
            $parts[] = $filter + 1;
        }
    }

    return implode(' ', $parts);
}

Leave a Reply

Your email address will not be published. Required fields are marked *