Search code examples
phparraysajaxunset

Using unset() on an array, but it keeps the value


I'm trying to remove an object from an array if one of his properties is null or empty, this is the code.

The array has been sorted using this function:

function sortArray($c1, $c2)
{
    return ($c1->propertyToCheck < $c2->propertyToCheck);
}

In case it changes anything.

$myArray = array();
...
// Add values to the array here
...
usort($myArray,"sortArray");

for($i = 0; $i < count($myArray ); $i++)
{
    if(empty($myArray[$i]->propertyToCheck))
    {
        unset($myArray[$i]);

        // var_dump($myArray[$i]) returns NULL
    }
}

echo json_encode($myArray); 
// Returns the entire array, even with the values that shouldn't be there.

The code is inside a function but the array is created inside said function.

I'm using echo json_encode($myArray) to send the value back in AJAX, but the array sent is the entire array with every object inside it.


Solution

  • The count($myArray) is the "problem".
    Once the unset() is "reached" there is one element less in the array and therefore the next call to count($myArray) will return n-1 of the previous iteration -> your loop doesn't get to the end of the array.
    You have at least three choices (in ascending order of my preference)

    a)

    $maxIdx = count($myArray);
    for($i = 0; $i < $maxIdx; $i++) {
    

    b)

    foreach( $myArray as $key=>$obj ) {
        if(empty($obj->propertyToCheck)) {
            unset($myArray[$key]);
    

    c)

    $myArray = array_filter(
        $myArray,
        function($e) {
            return !empty($e->propertyToCheck); 
        }
    );
    

    (...and many more)

    see also: http://docs.php.net/array_filter