0

Im storing age values inside an array using array push,

foreach($arrayagevalues as $value){


$arrayage21to30 = array();
$arrayage31to40 = array(); 
if($value['Age'] >= 21 && $value['Age'] <= 30)
{
array_push($arrayage21to30, $value['Age']);
}

if($value['Age'] >= 31 && $value['Age'] <= 40)
{
array_push($arrayage31to40, $value['Age']);
}

}

at the end I want to count the total values stored inside my array in $arrayage21to30 ans $arrayage31to40. I used count($arrayage21to30); but it doesnt return the total number of array values inside my array.

Is there any way on how I can count values of an array or the approach of storing values inside my array is wrong?

2
  • How about your issue, the 2 variables should be defined outside foreach loop. Commented Jul 21, 2013 at 15:52
  • What do you mean by total values, do you mean sum, if yes, see the last part of my answer, I have updated it. Commented Jul 21, 2013 at 16:19

2 Answers 2

1

$arrayage21to30 and $arrayage31to40 should be out of foreach

just try this code:

 <?php
 $arrayage21to30 = array();
 $arrayage31to40 = array();
 foreach($arrayagevalues as $value)
 {

     if($value['Age'] >= 21 && $value['Age'] <= 30)
     {
         array_push($arrayage21to30, $value['Age']);
     }

     if($value['Age'] >= 31 && $value['Age'] <= 40)
     {
         array_push($arrayage31to40, $value['Age']);
     }
 }
 echo count($arrayage21to30), "\n";
 echo count($arrayage31to40), "\n";

if you want to calculate the sum, you can use arrray_sum:

 echo array_sum($arrayage21to30), "\n";
 echo array_sum($arrayage31to40), "\n";
Sign up to request clarification or add additional context in comments.

1 Comment

I dont need the sum, I just need to count all the items inserted inside the array.
0

Define the variables outside the foreach loop.

$arrayage21to30 = array(); $arrayage31to40 = array();

then continue foreach

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.