How to subtract first value with last value in array [PHP]


I'm starting with PHP and I have to do this exercise: As a data I can not use php functions

The exercise consists of entering a number through a form, this number indicates the length of the array and filling the array with random numbers. Once the array is created, subtract the first value of the array with the last one, the second with the penultimate and so on. Either even or odd the length of the array.

But I can not think of any way to do this last: (

What I have done:

echo 'Array: <br>';



    echo $array[$i].' | ';


echo '<br><br>';

    echo $resta[]=$array[$i]-$array[$narray-1].'|';

asked by SakZepelin 25.11.2018 в 19:02

2 answers


what you must subtract must be counting in the same way but inversely, if for example you have an array of length 5, in your first cycle you would be subtracting the position [length -0] (5 since your for counter starts in 0) this is the last position, in your second cycle you would be subtracting the position [length -1] that is position 4 because now your for counter is worth 1, and so with each cycle, you only need to make a condition for that you do it the way you need, since as I mentioned, you would subtract from the last position to the first one

answered by 25.11.2018 в 20:09

You're doing well to the point that you do not take well the length of $narray . The way to catch the length of an array in php is using count() which is equivalent to .length() of js .

$longitud = count($narray);


    echo $resta[]=$array[$i]-$array[($longitud-1) - $i].'|';

answered by 25.11.2018 в 19:18