Core Function CountValues
From Sputnik Wiki
(Difference between revisions)
(Created page with "<pre> CountValues( <array> ) </pre> === Description === Counts all the values of an array. Returns an array using the values of the input array as keys and their frequency in...") |
(→Example) |
||
Line 37: | Line 37: | ||
[hello] => 2 | [hello] => 2 | ||
[world] => 1 | [world] => 1 | ||
+ | } | ||
+ | */ | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Here is an example with one or more arrays, which have similar values in it: | ||
+ | Use $lower = true/false to ignore/set case sensitivity. | ||
+ | |||
+ | <syntaxhighlight lang="sputnik"> | ||
+ | $res = iCountValues ($ar1); | ||
+ | printr($res); | ||
+ | |||
+ | function iCountValues($arr, $lower = true) | ||
+ | { | ||
+ | $arr2 = array(); | ||
+ | if($arr['0'] !~ Array) | ||
+ | $arr = array($arr); | ||
+ | foreach($arr as $k => $v) | ||
+ | @{ | ||
+ | foreach($v as $v2) | ||
+ | @{ | ||
+ | if($lower == true) | ||
+ | $v2 = lc($v2); | ||
+ | if(!IsIndexSet($arr2, $v2)) | ||
+ | $arr2[$v2] = 1; | ||
+ | else | ||
+ | $arr2[$v2]++; | ||
+ | } | ||
+ | } | ||
+ | return $arr2; | ||
+ | } | ||
+ | /* | ||
+ | // Prints | ||
+ | ARRAY | ||
+ | { | ||
+ | [red] => 3 | ||
+ | [green] => 3 | ||
+ | [yellow] => 4 | ||
+ | [blue] => 2 | ||
+ | [brown] => 2 | ||
+ | [white] => 1 | ||
+ | [black] => 1 | ||
} | } | ||
*/ | */ |
Revision as of 10:06, 31 August 2013
CountValues( <array> )
Contents |
Description
Counts all the values of an array.
Returns an array using the values of the input array as keys and their frequency in input as values.
Parameters
array
The array to use.
Return Value
Success: new array
Failure: empty array
Remarks
None.
Example
$array = array(1, "hello", 1, "world", "hello"); printr(CountValues($array)); /* // Prints ARRAY { [1] => 2 [hello] => 2 [world] => 1 } */
Here is an example with one or more arrays, which have similar values in it: Use $lower = true/false to ignore/set case sensitivity.
$res = iCountValues ($ar1); printr($res); function iCountValues($arr, $lower = true) { $arr2 = array(); if($arr['0'] !~ Array) $arr = array($arr); foreach($arr as $k => $v) @{ foreach($v as $v2) @{ if($lower == true) $v2 = lc($v2); if(!IsIndexSet($arr2, $v2)) $arr2[$v2] = 1; else $arr2[$v2]++; } } return $arr2; } /* // Prints ARRAY { [red] => 3 [green] => 3 [yellow] => 4 [blue] => 2 [brown] => 2 [white] => 1 [black] => 1 } */