Question

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

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top