Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not super familiar with C++, but I'll try to give you a quick overview of arrays in PHP, then answer your question about summing.</p> <p>Every array in PHP can be thought of as an ordered map. Unlike C++, there are no restrictions on type, an array is simply a map from key to value.</p> <p>To create an array, you can use the following:</p> <pre><code>$arr = array(); </code></pre> <p>To add items to the array, there are two ways to do it. First, you can use the <code>[]</code> operator to add a new element on to the end of the array. The key for this element will be (highest int key + 1), with the first key starting at zero. For example:</p> <pre><code>$arr[] = 1; $arr[] = 2; $arr[] = 4; </code></pre> <p>At this point, <code>$arr</code> is now a map with the following keys / values:</p> <pre><code>0 =&gt; 1 1 =&gt; 2 2 =&gt; 4 </code></pre> <p>We can also add specific keys and values:</p> <pre><code>$arr[42] = 'cool'; $arr['foo'] = 'bar'; </code></pre> <p>At this point the map will look as follows:</p> <pre><code>0 =&gt; 1 1 =&gt; 2 2 =&gt; 4 42 =&gt; 'cool' 'foo' =&gt; 'bar' </code></pre> <p>There's <a href="http://us.php.net/manual/en/ref.array.php" rel="nofollow">quite a few functions</a> built in to PHP for working with arrays. For example, there are functions for sorting arrays (both by key and value, and in user defined ways), combining arrays, searching arrays, applying functions to all elements, reducing arrays, etc. Furthermore, the PHP construct <code>foreach</code> can be used to iterate over an array. Use it as follows:</p> <pre><code>foreach ($arr as $key =&gt; $value) { echo 'Value of key ' . $key . ' is ' . $value; } </code></pre> <p>Now, to address your question:</p> <blockquote> <p>What I want to do is to sum up all the values for an initial range of keys</p> </blockquote> <p>Take note that if you add values in order, they will be in order in the array. If this is not the case, sort the array beforehand, then do the following:</p> <pre><code>$sum = array_sum(array_slice($arr, 0, $n)); </code></pre> <p>Hope this helps!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload