anonymous
anonymous

Reputation: 67

Notice: Undefined offset: 4 in Php File

I am trying to execute the the palindrome program in php where i take input from 1 file in variable "name" and on the second file it checks weather the enter string is palindrome or not... It works fine but i got notice which says "Notice: Undefined offset: 4 in C:\xampp\htdocs\pali.php on line 9"

<?php
$name = $_POST["name"];
 echo "String: " . $name;
$myArray = array(); // php array
$myArray = str_split($name); //split the array
$len = sizeof($myArray); // get the size of array
$newString = " ";
for ($i = $len; $i >= 0; $i--) {
    $newString.= $myArray[$i];
}
echo "<br>";
if ($name == $newString) {

    $lambi  = strlen($name);
 //loop through it and print it reverse
for ( $i = $lambi - 1; $i >=0;$i-- )
{
    echo "Output: " . $name . " is a palindrome";
  echo $name[$i];
}
}
 else {
    echo "Output: " . $name . " is not a palindrome";
 }
?>

error is on this line $newString.= $myArray[$i];

Upvotes: 0

Views: 5902

Answers (3)

MadMarc
MadMarc

Reputation: 129

$len = sizeof($myArray); returns the size of the array, but PHP arrays are 0 indexed.

You should use $len = sizeof($myArray)-1;

Upvotes: 0

Danielius
Danielius

Reputation: 837

I think problem is that array counts from 0 [0,1,2,3] and what you get from sizeof counts from 1 ( 1,2,3,4). So, you need to use $len = sizeof($myArray)-1; to get what you want.

Upvotes: 0

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

For loop should be start from $len-1

if $name="aabbaa" then $len will be 6 but the $myArray have only index from 0 to 5 (total 6)

$len = sizeof($myArray); // get the size of array
$newString = " ";
for ($i = ($len-1); $i >= 0; $i--) { // it should be ($len-1)
    $newString.= $myArray[$i];
}

Upvotes: 2

Related Questions