Get specific number in array?!

I have an array looking like this:

Array
(
    [0] => 1,g,10,97
    [1] => 2,j,0,106
    [2] => 3,b,3,32
    [3] => 4,b,9,44
    [4] => 5,r,11,21
    [5] => 6,y,7,66
    [6] => 7,y,1,54
    [7] => 8,b,4,33
    [8] => 15,y,12,75
    [9] => 16,g,7,92
    [10] => 17,y,3,58
    [11] => 18,b,8,41
    [12] => 19,b,13,51
    [13] => 20,r,5,9
    [14] => 21,g,5,88
    [15] => 22,y,4,59
)

Now, I only want add the numbers after the second comma in each record together… How do I do so?

Please help and thanks in advance :slight_smile:

Please post the code you have so far

Well, I have this comma seperated string:

$str = '1,g,10,97,2,j,0,106,3,b,3,32,4,b,9,44,5,r,11,21,6,y,7,66,7,y,1,54,8,b,4,33,15,y,12,75,16,g,7,92,17,y,3,58,18,b,8,41,19,b,13,51,20,r,5,9,21,g,5,88,22,y,4,59';

I then explode this into an array like this:

$str = explode(",",$str);
$h = '';
$k = 0;
foreach($str as $value){
    $h .= ($k%4 == 3)?$value.';':$value.',';
    $k++;
}
$str = explode(";",substr($h,0,-1));

Thats it!

And that code gives you the array you posted in your first post.
I must say I don’t understand at all why you want an array like that, but anyway, you can:

  • add some code in the foreach you already have, to take every third element and add those together
    or
  • loop through the array in your first post, explode each row, and then take the third element and add them together.

But I’m not quite sure how to do so?

Try. Then if you can’t get it to work, post the code here and surely we can get you on the right track

Tryid this:

foreach($str as $result){
			$result = explode(',', $result, 2);
			echo $result.'<br>';
		}

THis gives an output like this:
Array
Array
Arra

Where to go from here?

An alternative way would be to use array functions to split the string into an array of arrays, each sub-array having four values, then sum the third value of each of those sub-arrays.


// Converts "1,2,3,4,5,6,7,8,9,10,11,12" to array(array("1","2","3","4"),array("5","6","7","8"),array("9","10","11","12"))
$arrays = array_chunk(explode(',', $str), 4);

// Pull out the third values to get array("3", "7", "11")
// Note: Requires PHP >= 5.3 for the anonymous function; could use create_function() or a loop for older PHP versions
$values = array_map(function($array){ return $array[2]; }, $arrays);

echo array_sum($values);

Reading: