crotech Posted December 27, 2007 Share Posted December 27, 2007 I have been looking at the PHP documentation and can't figure out the best method to count the frequency of values in an array. $fields is returned from a MySQL query and would look something like the following: $fields = array ( array( 'id' => '1', 'type' => 'text', 'height' => '100', 'width' => '300' ), array( 'id' => '2', 'type' => 'text', 'height' => '200', 'width' => '200' ), array( 'id' => '3', 'type' => 'image', 'height' => '150', 'width' => '300' ), array( 'id' => '4', 'type' => 'image', 'height' => '400', 'width' => '400' ), array( 'id' => '5', 'type' => 'logo', 'height' => '150', 'width' => '150' ) ); I need to return 3 values from the array: The number of fields of type 'text', 'image', and 'logo'. I'm new to multidimensional arrays and I'm having a hard time figuring out the best way to accomplish this. Thanks for any help! Quote Link to comment https://forums.phpfreaks.com/topic/83367-solved-count-values-in-an-array/ Share on other sites More sharing options...
p2grace Posted December 27, 2007 Share Posted December 27, 2007 Something like this should work. $text = 0; $image = 0; $logo = 0; foreach($fields as $array){ foreach($array as $key => $value){ if($value == $text){ $text++; } if($value == $image){ $image++; } if($value == $logo){ $logo++; } } } Quote Link to comment https://forums.phpfreaks.com/topic/83367-solved-count-values-in-an-array/#findComment-424142 Share on other sites More sharing options...
Psycho Posted December 27, 2007 Share Posted December 27, 2007 I don't think there is a built in function to achieve this. You would just need to create a simple function: <?php function countValues($array) { $count = array(); foreach ($array as $value) { $count[$value['type']]++; } return $count; } $valueCount = countValues($fields); ?> Using the array in your post $valueCount would have the following values: array( 'text' => 2, 'image' => 2, 'logo' => 1 ), Quote Link to comment https://forums.phpfreaks.com/topic/83367-solved-count-values-in-an-array/#findComment-424145 Share on other sites More sharing options...
crotech Posted December 27, 2007 Author Share Posted December 27, 2007 Thanks for the quick responses! I went with mjdamato's response and it tested out perfectly for what I needed. Quote Link to comment https://forums.phpfreaks.com/topic/83367-solved-count-values-in-an-array/#findComment-424150 Share on other sites More sharing options...
p2grace Posted December 27, 2007 Share Posted December 27, 2007 Great, would you mind marking the post as "Solved". Thanks Quote Link to comment https://forums.phpfreaks.com/topic/83367-solved-count-values-in-an-array/#findComment-424153 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.