1

I previously had a with counting the array after exploding it, which was solved using array_filter but now when i echo the elements on the array it gives me undefined offset error

$exclude=array();
$exclude[0]="with";
$exclude[1]="do";

$search="moving on with my car";
$sch1 = str_replace($exclude,"", trim($search));
$sch2 = explode(" ",trim($sch1));
$sch = array_filter($sch2);
// The value of the count is actually 4

// But when i try to display throws an indefined offset error
echo $sch[0]; 
echo $sch[1]; 
echo $sch[2]; // Throwing an "Undefined offset: 2" Error

Any help will be appreciated . Thanks

2
  • please show what you wnat output? you have replaced $sch[2]; with "" Commented Mar 8, 2014 at 6:16
  • Thanks, i wanted to output "moving on my car", and its been solved Commented Mar 8, 2014 at 6:40

1 Answer 1

6

array_filter() removes all entries of the array that equals FALSE, thereby creating a gap in your array.

This is what $sch2 contains:

Array
(
    [0] => moving
    [1] => on
    [2] => 
    [3] => my
    [4] => car
)

When you apply array_filter() on $sch2, you'll get an array that looks like this:

Array
(
    [0] => moving
    [1] => on
    [3] => my
    [4] => car
)

As you can see, index 2 is not defined. You need to re-index the array numerically for this to work. You can use array_values() for this purpose:

$sch = array_values(array_filter($sch2));

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, i also checked myself now and its jst as u've said it, its true..will be chosen as answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.