0

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..

0

4 Answers 4

1

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];

3
  • Agreed. No use using push with PHPs bracket shortcut. Commented Aug 1, 2013 at 23:10
  • 1
    @Phix array_push() does have a use, but it's use case is rare in the real world (I have found). The key difference between the function and the bracketed-literal push is that the function accepts more than two arguments ;-) Commented Aug 1, 2013 at 23:12
  • Aye. For simple values, you said it yourself. ;-) Commented Aug 1, 2013 at 23:28
1

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]);
}
1
  • Yep. Turns out Warnings were off. I use a different loop (for each) and I pull the index out of nested arrays. Commented Aug 1, 2013 at 23:15
1

$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)
}
1

An easier way to accomplish the same thing:

$output = array_chunk($data, 2);

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.