0

I have an array that is a object which I carry in session lifeFleetSelectedTrucksList I also have objects of class fleetUnit

class fleetUnit {
    public $idgps_unit = null;
    public $serial = null;
}

class lifeFleetSelectedTrucksList {
    public $arrayList = array();
}

$listOfTrucks = new lifeFleetSelectedTrucksList(); //this is the array that I carry in session
if (!isset($_SESSION['lifeFleetSelectedTrucksList'])) {
    $_SESSION['lifeFleetSelectedTrucksList'] == null; //null the session and add new list to it.
} else {
    $listOfTrucks = $_SESSION['lifeFleetSelectedTrucksList'];
}

I use this to remove element from array:

$listOfTrucks = removeElement($listOfTrucks, $serial);

And this is my function that removes the element and returns the array without the element:

function removeElement($listOfTrucks, $remove) {
    for ($i = 0; $i < count($listOfTrucks->arrayList); $i++) {
        $unit = new fleetUnit();
        $unit = $listOfTrucks->arrayList[$i];
        if ($unit->serial == $remove) {
            unset($listOfTrucks->arrayList[$i]);
            break;
        } elseif ($unit->serial == '') {
            unset($listOfTrucks->arrayList[$i]);
        }
    }
    return $listOfTrucks;
}

Well, it works- element gets removed, but I have array that has bunch of null vaues instead. How do I return the array that contains no null elements? Seems that I am not suing something right.

1

2 Answers 2

3

I think what you mean is that the array keys are not continuous anymore. An array does not have "null values" in PHP, unless you set a value to null.

$array = array('foo', 'bar', 'baz');
// array(0 => 'foo', 1 => 'bar', 2 => 'baz');

unset($array[1]);

// array(0 => 'foo', 2 => 'baz');

Two approaches to this:

  1. Loop over the array using foreach, not a "manual" for loop, then it won't matter what the keys are.
  2. Reset the keys with array_values.

Also, removing trucks from the list should really be a method of $listOfTrucks, like $listOfTrucks->remove($remove). You're already using objects, use them to their full potential!

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

Comments

1

You can use array_filter

<?php

$entry = array(
         0 => 'foo',
         1 => false,
         2 => -1,
         3 => null,
         4 => ''
      );

print_r(array_filter($entry));
?>

output:

Array
(
[0] => foo
[2] => -1
)

2 Comments

Well, is this normal? Should unset leave nulls behind?
Nope, It should not give null with arrays.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.