1

How can you convert the following code to PHP?

summat = [sum(arra[i:i+4]) for i in range(0,len(arra),4)]

My attempt

$summat = array()
foreach ( range(0, $arra.length, 4) as $i) {
        $summat = array ( array_sum( array_slice( $array, $i, $i+5) ) )   // don't know how to append the sums the array

2 Answers 2

4
$sum = array();
foreach(range(0, count($a), 4) as $i)
   $sum []= array_sum(array_slice($a, $i, 4));

"[]=" is an append-to-array operator

slice's second parameter is slice length, not the last index

or even simpler

$sum = array_map('array_sum', array_chunk($a, 4));
Sign up to request clarification or add additional context in comments.

Comments

1

To append a value to an array, use:

$summat[] = array_sum(...);

The PHP way of doing ranges is similar to the C way:

for($i = 0; $i < count($arra); $i += 4) {
    // ...
}

Comments

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.