PHP: Count-IF for Arrays - php

What would be the most efficient way of counting the number of times a value appears inside an array?
Example Array ('apple','apple','banana','banana','kiwi')
Ultimately I want a function to spit out the percentages for charting purposes
(e.g. apple = 40%, banana = 40%, kiwi = 20%)

Just put it through array_count_values. The percentages should be easy...
$countedArray = array_count_values($array);
$total = count($countedArray);
foreach ($countedArray as &$number) {
$number = ($number * 100 / $total) . '%';
}

Use array_count_values():
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

$a = Array ('apple','apple','banana','banana','kiwi');
$b = array_count_values($a);
function get_percentage($b,$a){
$a_count = count($a);
foreach ($b as $k => $v){
$ret[$k] = $v/$a_count*100."%";
}
return $ret;
}
$c = get_percentage($b,$a);
print_r($c);

Related

SUM of array with the same variable php

I have a dynamic variable a with different values
$a = (1,2,3,4,5);
$a = (2,3,4,5,6);
I want a result that will sum each index of each array
$a = (3,5,7,9,11);
while($row=mysqli_fetch_array($sql)){
$a = explode(',',$row['array']); //array with same variable name
}
You could use array_map:
$a = array();
while($row=mysqli_fetch_array($sql)){
$a = array_map(function ($x, $y) { return $x + $y; }, $a, explode(',',$row['array']));
}
print_r($a);
Assuming your code returns rows of
$row['array'] = '1,2,3,4,5';
$row['array'] = '2,3,4,5,6';
The output will be:
Array
(
[0] => 3
[1] => 5
[2] => 7
[3] => 9
[4] => 11
)
May be below code will help you out
$a = array(1,2,3,4,5,4,5);
$b = array(2,3,4,5,6,7,3);
foreach($a as $k=>$v)
{
$temp = $a[$k]+$b[$k];
$c[] = $temp;
}
print_r($c);

php how to sort the values in multiple arrays in the order of frequency

I have an array containing multiple arrays like
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
I want to sort the values in multiple arrays in the order of frequency and put them into another array let's say $B.
The values in $B is "1","1","1","3","3","0","2","4","5","6","7","8".
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
//Merging above array in to one array
$merged = array_values(call_user_func_array('array_merge', $A));
//Getting occurrence count
$counts = array_count_values($merged);
//Sort by count
arsort($counts);
//Adding to required array
$B = array();
foreach ($counts as $k => $v)
for($i=1;$i<=$v;$i++)
$B[] = $k;
echo "<pre>";
print_r($B);
echo "</pre>";
Result
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 3
[4] => 3
[5] => 0
[6] => 8
[7] => 7
[8] => 5
[9] => 2
[10] => 4
[11] => 6
)
First merge all arrays
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$resultado = array_merge($array1, $array2);
see -> http://php.net/manual/es/function.array-merge.php
Second sort the big array
arsort($resultado );
see -> http://php.net/manual/es/array.sorting.php
Use a hash table to count the frequency of each number, and then store them in the decreasing order of frequency in array $B, like this:
$hash_table = array();
foreach($A as $array){
foreach($array as $value){
if(empty($hash_table[$value])){
$hash_table[$value] = 1;
}else{
$hash_table[$value] += 1;
}
}
}
arsort($hash_table);
$B = array();
foreach($hash_table as $key => $value){
for($i = 0; $i < $value; ++$i){
$B[] = $key;
}
}
var_dump($B); // to see the contents of array $B
If order of same occurance count items isn't important, you can use:
// Merge all arrays
$counts = array_count_values(call_user_func_array('array_merge', $A));
// Sort by occurance
arsort($counts);
// Add [value] to new array [occurance] times
$B = array();
array_walk($counts, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);
Output
1,1,1,3,3,0,8,7,5,2,4,6
Array print in order of count and index:
$temp = array();
foreach($A as $b){
foreach($b as $c){
if(isset($tmep[$c])){
$tmep[$c]++;
}else{
$tmep[$c] = 1;
}
}
}
function SortArrayByKeyThanValue (&$pArray, $pSortMethodForKey = SORT_ASC, $pSortMethodForValue = SORT_DESC){
# check user input: sorting is not necessary
if (count($pArray) < 2)
return;
# define $k and $v as array_multisort() needs real variables, as user input is put by reference
$k = array_keys ($pArray);
$v = array_values($pArray);
array_multisort(
$v, $pSortMethodForValue,
$k, $pSortMethodForKey
);
$pArray = array_combine($k, $v);
}
SortArrayByKeyThanValue($tmep);
$B = array();
array_walk($tmep, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);

Trouble finding odd results of an array

I can't seem to find the answer to these problem. I have the following php code.
$r = 1,2,3,4,5,6 and so on
and i want to get the number like this
$result = 1,3,5
or if i have
$s = b,c,d,e,f,g,h,i...and so on
the result should be
$results c,e,g,i
Pretty easy with numbers, the trick with letters is to use ord()
$arr = array(1,2,3,4,5,6);
$arr = array_filter ($arr, function ($number) {
return $number % 2;
});
print_r($arr);
$arr = array('a', 'b', 'c', 'd', 'e');
$arr = array_filter ($arr, function ($letter) {
return ord($letter) % 2;
});
print_r($arr);
Output :
Array (
[0] => 1
[2] => 3
[4] => 5
)
Array (
[0] => a
[2] => c
[4] => e
)
And here is a generic solution, working with both letters and numbers :
$arr = array_filter ($arr, function ($value) {
$value = is_int($value) ? $value : ord($value);
return $value % 2;
});
This will work:
$a = array(1,2,3,4,5,6);
foreach($a as $k => $v){
if($k&1){
unset($a[$k]);
}
}
print_r($a);

Mixing two arrays together in PHP

Lets say I have two arrays like this:
$array1(one, two, three);
$array2(four, five, six);
And I want the result to be like this:
[0] -> one four
[1] -> two five
[2] -> three six
How should I do this?
You can use array_map function providing your two arrays in parameter :
<?php
$array1=Array("one", "two", "three");
$array2=Array("four", "five", "six");
$res=array_map(function($r1, $r2) {return "$r1 $r2";}, $array1, $array2);
print_r($res);
Result
Array
(
[0] => one four
[1] => two five
[2] => three six
)
try this
function array_interlace() {
$args = func_get_args();
$total = count($args);
if($total < 2) {
return FALSE;
}
$i = 0;
$j = 0;
$arr = array();
foreach($args as $arg) {
foreach($arg as $v) {
$arr[$j] = $v;
$j += $total;
}
$i++;
$j = $i;
}
ksort($arr);
return array_values($arr);
}
$array1=array('one', 'two', 'three');
$array2=array('four', 'five',' six');
print_r(array_interlace($array1,$array2));

How to make this format of array in PHP?

I want to make an array in PHP but it should be in specific format such this:
array(1, 5, 3)
I mean, I have the values 1, 5 and 3 from my database, so I had to loop it with the use of array_push
$a=array();
foreach( $db_nums as $db_num ){
array_push($a, $db_num);
}
print_r($a);
but it outputs:
Array ( [0] => 1 [1] => 5 [2] => 3 );
i want it to be only:
array(1, 5, 3 );
Any ideas how? Thanks a lot for any help!
Just use the below code:
$Array = array(1,2,3);
Edit:
$a = array();
foreach( $db_nums as $db_num )
{
$a[] = $db_num;
}
print_r($a);
$db_nums = array(1, 2, 3); //pointless example, but comes from DB
$a = array();
foreach ($db_nums as $n) {
$a[] = $n;
}
var_export($a);
That will output:
array (
0 => 1,
1 => 2,
2 => 3,
)
Which is about as close as you're going to get without writing your own function to do it.
(Also note that in this example, you could just directly do var_export($db_nums).)
<?php $array = array("foo", "bar", "hallo", "world"); var_dump($array); ?>
You can use that

Categories