Combine associative array with condition in php - php

I have an array like this
Array
(
[14] => 2
[28] => 1
)
what i need is an array with index value upto 31 where in ,except index 14 and 28 the value should be 0(zero) and the index 14 and 28 should have the value 2 and 1 respectively.
please help me with this.
thanks in advance

There are more ways how to do it, for example:
<?php
$arr = array(14 => 2, 28 => 1);
$res = array();
for ($i = 0; $i <= 31; $i++) {
$res[$i] = isset($arr[$i]) ? $arr[$i] : 0;
}
echo '<pre>';
print_r($res);

Do you want like this:-
<?php
$a = array_fill(0, 31, 0);
$a[14] = 2;
$a[28] = 1;
print_r($a);
?>
Output:- https://eval.in/913931
Reference:- PHP: array_fill - Manual

Related

How do I count the sum of specified sum in $total

e.g. if I pass $total = 2 then it should calculate the sum of first
two arrays.
sub1 + sub2
**HERE IS MY CODE **
<?php
$num = 2;
$array = array();
$total = 2;
for($x=1;$x<=$num;$x++)
{
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$array[] = $result;
}
echo '<pre>'; print_r($array);
?>
try
<?php
$array = array();
$total = 2;
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$temp_array = array_slice($result, 0, $total);
$sum = array_sum($temp_array);
print_r($result);
echo "sum of $total array is : ".$sum;
Output would be like :
Array
(
[sub1] => 30
[sub2] => 19
[sub3] => 56
[sub4] => 47
[sub5] => 6
)
sum of 2 array is : 49
https://eval.in/539097
should do the trick. hope it helps :)
simply you can use for loop like this
$sum=0;
for($i=0;$i<$total;$i++){
$sum+=$result[$i];
}

How do I get sum of distinct value from php list that was exploded? [duplicate]

This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 7 months ago.
I would like to count the occurrence of each duplicate item in an array and end up with an array of only unique/non duplicate items with their respective occurrences.
Here is my code; BUT I don't where am going wrong!
<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
//$previous[value][Occurrence]
for($arr = 0; $arr < count($array); $arr++){
$current = $array[$arr];
for($n = 0; $n < count($previous); $n++){
if($current != $previous[$n][0]){// 12 is not 43 -----> TRUE
if($current != $previous[count($previous)][0]){
$previous[$n++][0] = $current;
$previous[$n++][1] = $counter++;
}
}else{
$previous[$n][1] = $counter++;
unset($previous[count($previous)-1][0]);
unset($previous[count($previous)-1][1]);
}
}
}
//EXPECTED VALUES
echo 'No. of NON Duplicate Items: '.count($previous).'<br><br>';// 7
print_r($previous);// array( {12,1} , {21,2} , {43,6} , {66,1} , {56,1} , {78,2} , {100,1})
?>
array_count_values, enjoy :-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
Result:
No. of NON Duplicate Items: 7
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
if you want to try without 'array_count_values'
you can do with a smart way here
<?php
$input= array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$count_values = array();
foreach ($input as $a) {
#$count_values[$a]++;
}
echo 'Duplicates count: '.count($count_values);
print_r($count_values);
?>
Simplest solution (that's where PHP rocks) - ONLY duplicates:
$r = array_filter(array_count_values($array), function($v) { return $v > 1; });
and check:
print_r($r);
Result $r:
[43] => 6
[21] => 2
[78] => 2
If you have a multi-dimensional array you can use on PHP 5.5+ this:
array_count_values(array_column($array, 'key'))
which returns e.g.
[
'keyA' => 4,
'keyB' => 2,
]
I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.
function strInArray($haystack, $needle) {
$i = 0;
foreach ($haystack as $value) {
$result = stripos($value,$needle);
if ($result !== FALSE) return TRUE;
$i++;
}
return FALSE;
}
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
for ($i = 0; $i < count($array); $i++) {
if (strInArray($array,$array[$i])) {
unset($array[$i]);
}
}
var_dump($array);
You can also use it with text items array, u will get number of duplicates properly, but PHP shows
Warning: array_count_values(): Can only count STRING and INTEGER
values!
$domains =
array (
0 => 'i1.wp.com',
1 => 'i1.wp.com',
2 => 'i2.wp.com',
3 => 'i0.wp.com',
4 => 'i2.wp.com',
5 => 'i2.wp.com',
6 => 'i0.wp.com',
7 => 'i2.wp.com',
8 => 'i0.wp.com',
9 => 'i0.wp.com' );
$tmp = array_count_values($domains);
print_r ($tmp);
array (
'i1.wp.com' => 2730,
'i2.wp.com' => 2861,
'i0.wp.com' => 2807
)
Count duplicate element of an array in PHP without using in-built
function
$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
for($i=0;$i<$arrlength-1;$i++)
{
$key=$arraychars[$i];
if($arrCount[$key]>=1)
{
$arrCount[$key]++;
} else{
$arrCount[$key]=1;
}
echo $arraychars[$i]."<br>";
}
echo "<pre>";
print_r($arrCount);
There is a magical function PHP is offering to you it called in_array().
Using parts of your code we will modify the loop as follows:
<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
if (in_array($array[$arr], $arr2)) {
++$counter;
continue;
}
else{
$arr2[] = $array[$arr];
}
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>
The above code snippet will return the number total number of repeated items i.e. form the sample array 43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.
You can do it using foreach loop. (Demo)
$array = array(1,2,3,1,2,3,1,2,3,4,4,5,6,4,5,6,88);
$set_array = array();
foreach ($array as $value) {
$set_array[$value]++;
}
print_r($set_array);
Output:
Warning: Undefined array key 1 in /in/aGPqe on line 6
Warning: Undefined array key 2 in /in/aGPqe on line 6
Warning: Undefined array key 3 in /in/aGPqe on line 6
Warning: Undefined array key 4 in /in/aGPqe on line 6
Warning: Undefined array key 5 in /in/aGPqe on line 6
Warning: Undefined array key 6 in /in/aGPqe on line 6
Warning: Undefined array key 88 in /in/aGPqe on line 6
Array
(
[1] => 3
[2] => 3
[3] => 3
[4] => 3
[5] => 2
[6] => 2
[88] => 1
)
I came here from google looking for a way to count the occurrence of duplicate items in an array. Here is the way to do it simply:
$colors = ["red", "green", "blue", "red", "yellow", "blue"];
$unique_colors = array_unique($colors); // ["red", "green", "blue", "yellow"]
$duplicates = count($colors) - count($unique_colors); // 6 - 4 = 2
if ($duplicates == 0) {
echo "There are no duplicates";
}
echo "No. of Duplicates: " . $duplicates;
// Output: No. of Duplicates are: 2
How array_unique() works?
It elements all the duplicates.
ex:
Lets say we have an array as follows -
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");
When you do $cars = array_unique($cars);
cars will have only following elements.
$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");
To read more: https://www.php.net/manual/en/function.array-unique.php
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5
$input = [1,2,1,3,2,4,10];
//if give string
//$input = "hello hello how are you how hello";
//$array = explode(' ',$input);
$count_val = [];
foreach($array as $val){
$count_val[$val]++;
}
print_r($count_val);
//output ( [1] => 2 [2] => 2 [3] => 1 [4] => 1 [10] => 1 )

php dynamic number array add missing values defined by a range

I have looked and googled many times I found a few posts that are simular but I can not find the answer Im looking for so I hope you good people can help me.
I have a function that returns a simple number array. The array number values are dynamic and will change most frequently.
e.g.
array(12,19,23)
What I would like to do is take each number value in the array, compare it to a set range and return all the lower value numbers up to and including the value number in the array.
So if I do this:
$array = range(
(11,15),
(16,21),
(22,26)
);
The Desired output would be:
array(11,12,16,17,18,19,22,23)
But instead I get back all the numbers in all the ranges.
array(11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26)
What would be a simple solution to resolve this?
Try this code
$range = array(
array(11,15),
array(16,21),
array(22,26),
);
$array = array(12,19,23);
$result = array();
foreach($range as $key=>$value)
{
//$range1 =$range[$key];
$min = $range[$key][0];
$max = $range[$key][1];
for($i = $min;$i<=$max;$i++)
{
if($i <= $array[$key])
{
array_push($result,$i);
}
}
}
echo "<pre>";print_r($result);
Iterate over each element, find the the start and end values you need to include, and append them to the output array:
$a = array(12,19,23);
$b = array(
range(11,15),
range(16,21),
range(22,26)
);
$c = array();
foreach ($a as $k => $cap) {
$start = $b[$k][0];
$finish = min($b[$k][count($b[$k])-1], $cap);
for ($i = $start; $i <= $finish; $i++) {
$c[] = $i;
}
}
print_r($c);
prints
Array
(
[0] => 11
[1] => 12
[2] => 16
[3] => 17
[4] => 18
[5] => 19
[6] => 22
[7] => 23
)
My solution is probably not the most efficient, but here goes:
$numbers = array(12,19,23);
$ranges = array(
array(11,15),
array(16,21),
array(22,26)
);
$output = array();
// Loop through each of the numbers and ranges:
foreach($numbers as $num) {
foreach($ranges as $r) {
if ($num >= $r[0] && $num <= $r[1]) {
// This is the correct range
// Array merge to append elements
$output = array_merge($output, range($r[0], $num));
break;
}
}
}
// Sort the numbers if you wish
sort($output, \SORT_NUMERIC);
print_r($output);
Produces:
Array
(
[0] => 11
[1] => 12
[2] => 16
[3] => 17
[4] => 18
[5] => 19
[6] => 22
[7] => 23
)

Count array values in a loop and then add together

I'm struggling with this for a while now and getting more important at the moment.
Lets say we have a array with the values
Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
)
when i loop this array in a foreach loop i want the first result 11 second result 36 (11 + 25) 3rd result 38 (11 + 25 + 2) 4rd result 45 (11 + 25 + 2 +7) etc....
this way i get cumulative results
This is what i tried so far:
<?php
foreach(array_slice(weeks($start_week), 0, 26) as $week):
$gewasregistratie["gezette_vruchten_cumulatief"][$week] = $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week] + $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week-1];
$gewasregistratie["gezette_vruchten_cumulatief"][$week] += $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week];
endforeach;
foreach(array_slice(weeks($start_week), 0, 26) as $week):
echo "<td week='".$week."' class='part1'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
foreach(array_slice(weeks($start_week), 26, 51) as $week):
echo "<td week='".$week."' class='part2'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
?>
Can someone help me in the right direction ?
Simple like boiling a egg. Try this code
$test = array(11,25,2,7);
$count = 0;
foreach($test as $i=>$k)
{
$count +=$k;
echo $count." ";
}
Output:
11 36 38 45
Suggestion: you can store output in another array also.
Try this:
$a = array(11,25,2,7);
$c = 0;
foreach($a as $k=>$v){
$c += $v;
$b[] = $c;
}
print_r($b);
you will get result in array like below :
Array ( [0] => 11 [1] => 36 [2] => 38 [3] => 45 )
The simplest way
$original = array(23, 18, 5, 8, 10, 16);
$total = array();
$runningSum = 0;
foreach ($original as $number) {
$runningSum += $number;
$total[] = $runningSum;
}
var_dump($total);
$array = array( 11, 25, 2, 7 );
$results = array();
foreach ($array AS $i => $v) {
if (empty($results)) {
$results[] = $v;
} else {
$results[] = $v + $results[$i - 1];
}
}
Something like this.
Try this code
$arr=Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$sum=0;
foreach($arr as $k=>$val)
{
echo "<br>".$sum+=$val;
}
Find below solution
$arr = array(11,25,2,7);
$sum =0;
foreach($arr as $val){
$sum +=$val;
echo $sum ."<br/>";
}
If you are looking to iterate over a single-dimensional array as your question was initially worded, array_map would be your most efficient method:
function cascade($n) {
static $current = 0;
return $current += (int) $n;
}
$test = array(11,25,2,7);
$result = array_map('cascade', $test);
/**
* You could also assign back to the original array like:
* $test = array_map('cascade', $test);
*/
If you are looking to do something in a multi-dimensional array, using array_walk would be the solution there. Would you like an example?
Try this.
$myArray = Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$total = 0;
for($i=1; $i <= count($myArray); $i++) {
$total += $myArray[$i];
echo $total . ", ";
$cumulativeArray[] = $total;
}
print_r($cumulativeArray);

php array_unique not working as expected

I am trying to learn how to use array_unique, so I made some sample code and I didn't get what I expected.
$array[0] = 1;
$array[1] = 5;
$array[2] = 2;
$array[3] = 6;
$array[4] = 3;
$array[5] = 3;
$array[6] = 7;
$uniques = array_unique($array, SORT_REGULAR);
for($i = 0; $i < count($uniques); $i++)
echo $uniques[$i];
For example this gives me the output of '15263' but not 7. After a few test I think that it stops looking after it finds the first duplicate. Is that what is supposed to happen?
Reason for $uniques output is
Array
(
[0] => 1
[1] => 5
[2] => 2
[3] => 6
[4] => 3
[6] => 7
)
Your array doesn't contain key 5, but in your for loop echo $uniques[$i]; not hold the value of echo $uniques[5];. that is the reason value 7 is missing.
Try this,
foreach($uniques as $unique){
echo $unique;
}
instead of
for($i = 0; $i < count($uniques); $i++)
OR, you can re-index the array using array_values($uniques) and use,
$uniques = array_values($uniques);
for($i = 0; $i < count($uniques); $i++)
echo $uniques[$i];
Since array_unique preserves the keys, you can’t access the array $uniques properly with a for loop. Either use a foreach loop or change the seventh line of your code to:
$uniques = array_values(array_unique($array, SORT_REGULAR));

Categories