Reputation: 1
I am trying to find a string in other string. I am not allowed to use any of str function. Therefore, I wrote this code! But it shows Undefined offset: 14 in C:\nn\htdocs\myfiles\PHPCode.php
on line 18.
I do not know what's wrong with this line.
if ($arr1[$j] == $arr2[$index])
The full code
<?php
$stringR = strtolower($_POST['name']);
$first = strtolower($_POST['First']);
$k = 0;
$index =0;
$firstfeq =0;
if (preg_match('/[0-9]/', $stringR)){
echo "ERROR:The String has numbers"."<br>";
exit;
}
if (( strlen($first) > 8 )){
echo "ERROR: Number of char in each input should be less than 8 char"."<br>";
exit;
}
$arr1 = str_split($stringR);
$arr2 = str_split($first);
for ($j = 0 ; $j <= sizeof($arr1) ; $j++) {
if ($arr1[$j] == $arr2[$index]){
if ($index <= (sizeof ($arr2))){
$k = 1;
$index++;
}else
{
$index = 0;
$k =0;
}
if (($index == sizeof($arr2)) && ( $k == 1)) {
$firstfeq++;
$index =0;
$k = 0;
}
}
}
echo "$first appears $firstfeq"."<br>";
?>
Upvotes: 0
Views: 757
Reputation: 1171
Since Arrays are indexed from 0, you should replace this line
for ($j = 0 ; $j <= sizeof($arr1) ; $j++) {
with
for ($j = 0 ; $j < sizeof($arr1) ; $j++) {
and similarly
if ($index <= (sizeof ($arr2))){
with
if ($index < (sizeof ($arr2))){
Upvotes: 1
Reputation: 1268
Change this:
for ($j = 0 ; $j <= sizeof($arr1) ; $j++) {
to this:
for ($j = 0 ; $j < sizeof($arr1) ; $j++) {
I bet $j is going 1 index above the total limit.
Upvotes: 1