[Solved] I dont know what to do with this PHP Code

[ad_1]

You get to the size of elements, which is 1. However, if your array has only one element, which is the case for 1-digit numbers, then sizeof($_array) === 1. Which means that the biggest possible index you can use is 0. You need to change your code to something like this:

<?php

    for ($num = 1; $num <= 20; ++$num){

        $_array1 = str_split($num);
        //print_r($_array1);
        //echo "<br/>";

        $_array2 = array_reverse($_array1);
        //print_r($_array2);
        //echo "<br/>";

        $i = 0;
        $j = 0;

        $different = false;
        while ((!$different) && ($i < sizeof($_array1))){
            if ($_array1[$i] == $_array2[$j]){
            ++$i;
            ++$j;
        } else {
            $different = true;
        }

        }

        if (!$different){
            echo "The number $num is a Palindrome Number";
        }
    }

?>

But you are inversing the array without a need to do so and you are looping for unnecessarily long. I propose this function to determine whether an array is a palindrome:

function isPalindrome($input) {
    $size = count($input);
    for ($index = 0; $index < $size / 2; $index++) {
        if ($input[$index] != $input[$size - $index - 1]) {
            return false;
        }
    }
    return true;
}

Note, that:

  • the function assumes that the keys of the array are numbers
  • the function uses a single array
  • the size of the array is stored into a local variable to not calculate it repeatedly
  • the cycle cycles until half of the array, since going beyond that is unnecessary, due to the symmetrical nature of the != operator
  • the function returns false when the first difference is found, to further optimize the checking
  • if there were no differences, the function returns true, representing that the input is a palindrome

3

[ad_2]

solved I dont know what to do with this PHP Code