Xeos
Xeos

Reputation: 6497

PHP array_push adding null instead of integer

I have an array output. It should have a set of tuples within it. I create those tuples on the run from the for loop. (Simplified version of my code - the logic is the same, but $ind is calculated in a more complex way)

$output = Array();
$length = count($data);
for ($i = 0; $i < $length; $i++) {
    $ind = $i - ($i % 2);
    array_push($output[$ind], $data[$i]);
}

Here is the sample input ($data):

[10,2,123,4,34,6]

And a sample output ($output):

[[10,2],[123,4,],[34,6]]

But I get (not even empty arrays):

[,,] == [null,null,null]

$data[$i] is an integer. I tries to explicitly call intval() on it - still no luck. Also *array_push()* does not return anything after execution. No errors or warnings thrown..

Upvotes: 0

Views: 9092

Answers (4)

Expedito
Expedito

Reputation: 7795

An easier way to accomplish the same thing:

$output = array_chunk($data, 2);

Upvotes: 1

Amit Malakar
Amit Malakar

Reputation: 608

$output array is not initialized when using array_push(), try this

$data = array(10,2,123,4,34,6);
$output = Array();
$length = count($data);
for ($i = 0; $i < $length; $i++) {
    $ind = $i - ($i % 2);
    //array_push($output[$ind], $data[$i]);

    $output[$ind] = $data[$i];
}
var_dump(array_values($output));

Output

array(3) {
  [0] => int(2)
  [1] => int(4)
  [2] => int(6)
}

Upvotes: 1

lupatus
lupatus

Reputation: 4248

Turn on error reporting while developing (I suggest to set it to E_ALL), you'll see all the problems. You're trying to push values to non existing array - you have to check if array has been already created at index you want to push and create it if it does not exists. Additional problem in your code is that you're doing one loop too much (should be $i < $length) :

$output = Array();
$length = count($data);
for ($i = 0; $i < $length; $i++) {
    $ind = $i - ($i % 2);
    if (!isset($output[$ind])) $output[$ind] = array();
    array_push($output[$ind], $data[$i]);
}

Upvotes: 1

Xeos
Xeos

Reputation: 6497

From PHP documentation (http://php.net/manual/en/function.array-push.php):

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

The array was not initialized when the push was called.

Use $output[$ind][] = $data[$i];

Upvotes: 1

Related Questions