<?php
$array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
$result = [];
for ($i=0; $i < count($array) ; $i++) {
if (($i >=3 AND $i <= 6) OR $i=8){
array_push($result, $array[$i]*2);
} else {
array_push($result, $array[$i]*10);
}
}
var_dump($result);
?>
I want to multiply value in array that have key 3, 4, 5, 6, and 8 by 2, other than that key I want to multiply it by 10.
Tried change memory limit even to -1 (unlimited) but still give same error.
It seems the only problem is: you are changing the value of $i inside the if clause because of a missing =, it should be $i==8 instead of $i=8, a working script with some minor changes would be:
<?php
$array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
$result = [];
$length = count($array);
for($i=0; $i < $length ; $i++) {
if (($i >=3 AND $i <= 6) OR $i==8){
$val = $array[$i] * 2;
} else {
$val = $array[$i] * 10;
}
array_push($result, $val);
}
// output
echo "<pre>";
print_r($result);
echo "</pre>";
?>
This outputs:
Array
(
[0] => 100
[1] => 200
[2] => 300
[3] => 80
[4] => 100
[5] => 120
[6] => 140
[7] => 800
[8] => 180
[9] => 1000
)
change your if condition from: if (($i >=3 AND $i <= 6) OR $i=8){
to : if (($i >=3 AND $i <= 6) OR $i==8){
***You are not assigning a value to $i. You are checking its value. That's why you must use ==.
Related
I have this kind of problem that I can't get the same value in an array and separate the different value inside an array
I have done using for loop but it seems like my logic wasn't correct.
Value of $supplier_id is
Array (
[0] => 82
[1] => 82
[2] => 96
[3] => 96
[4] => 28
)
for($x = 0; $x < count($supplier_id); $x++){
for($i = 0; $i < count($supplier_id); $i++){
if($supplier_id[$x] == $supplier_id[$i]){
$same_supp[$x]['same_supp'] = $supplier_id[$x];
}else{
}
}
}
I want to store the values inside the array with the same value and separate the different value.
My expected output is
$same_supp[0] = array(0 => 82, 1 => 82);
$same_supp[1] = array(0 => 96, 1 => 96);
and separate the different value which is 28 and store it in different variable.
Group them, filter out the single occurrences, and remove the temporary keys.
Code: (Demo)
$array = [82, 82, 96, 96, 28];
foreach ($array as $v) {
$temp[$v][] = $v;
}
foreach ($temp as $a) {
if (count($a) != 1) {
$result[] = $a;
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 82,
1 => 82,
),
1 =>
array (
0 => 96,
1 => 96,
),
)
Since the inner loop ($i) also run on the same iteration as the outer loop ($x), it will not only find the duplicates, but also all of the elements.
You can fix it by skipping the check of the same item (when $i and $x are equal)
for($x = 0; $x < count($supplier_id); $x++){
for($i = 0; $i < count($supplier_id); $i++){
if ($x == $i) continue;
...
...
$ar is a sock of pairs. $n is the number of items in $ar. I have to match each number in the array with another if any of them match, its a pair. I have to then return the count of matched items. I have done it below but the answer is one less than what it should be. Example
n:9
ar: 10 20 20 10 10 30 50 10 20
I get output 2 instead of 3.
function sockMerchant($n, $ar) {
$pair =0;
$j=0;
for($i=0; $i< count($ar); $i++)
{
for($j=$i+1; $j< count($ar); $j++)
{
if ( isset( $ar[$j]) && isset( $ar[$i])) {
if ($ar[$i]== $ar[$j])
{
unset($ar[$i]);
unset($ar[$j]);
$pair+=1;
$i=0;
break;
}
}
}
}
return count($ar);
}
Instead of what you are doing there is shortcut to achieve the same,
$temp = array_count_values($arr); // count number of occurences
echo count(array_filter($temp, function($value){ // filter in not greater than 1
return $value > 1;
}));
The above snippet will give you all the pairs which are not only once.
Here is an one more alternative for your snippet,
$temp = array_count_values($arr); // count number of occurences
$e = array_reduce($temp, function ($carry, $item) {
$carry += ($item > 1 ? intval($item / 2) : 0);
return $carry;
});
echo $e;die;
Working demo.
$ar = [10, 20, 20, 10, 10, 30, 50, 10, 20];
$pairIndex = [];
$count = 0;
foreach ($ar as $key => $item) {
// Start comparing from the next element
for ($i = ($key + 1); $i < count($ar); $i++) {
if ($item == $ar[$i] && !in_array($key, $pairIndex)) {
$pairIndex[] = $key;
$pairIndex[] = $i;
$count++;
}
}
}
echo "Pairs: " . $count;
This will give you the number of pairs.
$arr = array(10, 20, 20, 10, 10, 30, 50, 10, 20);
$counts = array_count_values($arr); // count number of occurences
array_walk($counts, function(&$x) {$x = intdiv($x, 2);}); //divide each element
//by 2 (integer division), so now you have pairs of each element
echo array_sum($counts); //sum the pairs
Using your initial array, it echoes 3.
simple example what happens to your array:
$ar = array(0, 10, 20, 30, 40, 50 , 60, 70, 80, 90);
$lnPointer = 2;
print_r($ar);
// Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 [6] => 60 [7] => 70 [8] => 80 [9] => 90 )
echo "<HR>";
echo $ar[$lnPointer];
echo "<HR>";
unset( $ar[$lnPointer]);
print_r($ar);
// Array ( [0] => 0 [1] => 10 [3] => 30 [4] => 40 [5] => 50 [6] => 60 [7] => 70 [8] => 80 [9] => 90 )
echo "<HR>";
echo $ar[$lnPointer];
after unsetting you get an undefined index
If you want total matched pair count then you should return $pair. But you are returning count($ar) which can not be correct in all the possible scenarios. Check the below code with output and new set of data:
<?php
function sockMerchant($n, $ar) {
$pair =0;
$j=0;
for($i=0; $i< $n; $i++)
{
for($j=$i+1; $j< $n; $j++)
{
if ( isset( $ar[$j]) && isset( $ar[$i])) {
if ($ar[$i]== $ar[$j])
{
unset($ar[$j]);
unset($ar[$i]);
$pair+=1;
$i=0;
break;
}
}
}
}
echo '<pre>'; print_r($ar);
return $pair.'--'.count($ar);
}
$a = [10, 20, 20, 10, 10, 30, 50, 10, 20, 80, 40];
$n = 11;
$b = sockMerchant($n, $a);
var_dump($b);
// Output:
/*
Array
(
[5] => 30
[6] => 50
[8] => 20
[9] => 80
[10] => 40
)
string(4) "3--5"
*/
?>
Demo
For each element in the array, I need to add value of previous element to it's current element. Example:
Array
(
[0] => 460
[1] => 25
[2] => 25
[3] => 25
[4] => 25
[5] => 25
[6] => 25
)
How can I get like following:
Array
(
[0] => 460
[1] => 485
[2] => 510
[3] => 535
[4] => 560
[5] => 585
[6] => 610
)
Any ideas?
Here's a quicker solution compared to the rest:
foreach ($a as $i => $val) {
// make sure the current item is not the first one.
// because the first one is the base number
if ($i > 0) {
// Update current $i (INDEX) by
// adding the previous value ($a[$i -1]) with the current value ($val)
$a[$i] = $a[$i - 1] + $val;
}
}
As 0 is the first value, we can't increment before it :) hence the if statement
And here is a demo: Example
It doesn't matter about what looping method you use, it's how you apply it. Look, here's the exact same thing done in a for loop:
for($i = 0; $i < count($a); $i++) {
if($i > 0) {
$a[$i] = $a[$i - 1] + $a[$i];
}
}
It all comes down to the preference of the coder using it.
Both of those loops return the correct data:
Array
(
[0] => 460
[1] => 485
[2] => 510
[3] => 535
[4] => 560
[5] => 585
[6] => 610
)
Like this?
$source = array(460, 25, 25, 25, 25, 25, 25);
$result = array();
$last = 0;
foreach($source as $s){
$last = $result[] = $s+$last;
}
$previous = 0;
foreach ($a as $key => &$value)
$previous = $value = $previous + $value;
or
$sum = 0;
foreach ($a as $key => &$value)
{
$sum += $value;
$value = $sum;
}
Get the value of the previous index (do check if index > 0), and add it to the current value.
$values = array(
460,
25,
25,
25,
25,
25,
25
);
foreach($values as $key => &$value){
if($key > 0){
$prev_value = $values[$key-1];
$value += $prev_value;
}
}
echo print_r($values);
$array1 = (460, 25, 25, 25, 25, 25, 25);
function calculateAdjecentSum($array1)
{
$array2 = array();
$pointer = 0;
foreach ($array1 as $number) {
$sum = $pointer + $number;
$array2[] = $sum;
$pointer = $sum;
}
return $array2;
}
It's enough to use for loop:
<?php
$array = array
(
0 => 460,
1 => 25,
2 => 25,
3 => 25,
4 => 25,
5 => 25,
6 => 25,
);
for ($i=1, $c = count($array); $i<$c; ++$i) {
$array[$i] += $array[$i-1];
}
var_dump($array);
I have no idea why all other answers use foreach loop in this case as for in my opinion is better to do that (no conditions, no temporary variables, no unset references from foreach).
You can do like this
<?php
$yourarray = array(460, 25, 25, 25, 25, 25, 25);
$l = 0;
foreach($yourarray as $b){
$l = $b+$l;
echo $last;
}
Outputs 460485510535560585610
Try this :
<?php
$array = array( 460, 25, 25, 25, 25, 25, 25);
$result = array();
for ($i=count($array);$i>0; $i--){
$result[($i-1)] = array_sum($array);
array_pop($array);
}
echo "<pre>";
ksort($result);
print_r($result);
?>
Output :
Array
(
[0] => 460
[1] => 485
[2] => 510
[3] => 535
[4] => 560
[5] => 585
[6] => 610
)
I have an array i want to find max value for both positive and negative value.
The expected result would be -13.2 and 7.8
$array = array
(
[0] => -13.2
[1] => -14.5
[2] => -14.3
[3] => -13.7
[4] => -13.8
[5] => -14.6
[6] => 6.4
[7] => 6.9
[8] => 7.2
[9] => 6.9
[10] => 7.8
[11] => 6.9
[12] => 6.3
[13] => 7.2
[14] => 6.9
[15] => 6.8
)
$maxrl='';
for($i=1,$j=0;$i<=count($array);$i++,$j++)
{
if($maxr <= $array[$j])
{
if(($maxr < $array[$j]) && ($maxrl != ''))
{
$maxrl='';
$maxrl.="L".$k.",";
}
else
{
$maxrl.="L".$k.",";
}
$maxr = $max_array[$j];
}
$k++;
}
echo "<tr><td >'.$maxr.'</td><td>'.substr($maxrl,0,-1).'</td><>/tr>";
You can simply use max & min functions,
echo "Max Value:- ".max($array); // Max Value:- 7.8
echo "Min Value:- ".min($array); // Min Value:- -14.6
UPDATED: If you really want max from both negative & positive values,
$positive = array_filter($array, function ($v) {
return $v > 0;
});
$negative = array_filter($array, function ($v) {
return $v < 0;
});
echo "Max in positive Value:- ".max($positive); // Max in positive Value:- 7.8
echo "Min in negative Value:- ".min($negative); // Max in negative Value:- -13.2
For the positive maximum just take
$max = max($array);
The highest minimum is a bit more complex:
$minArray = array();
foreach ( $array as $val )
if ( $val < 0 )
$minArray[] = $val;
$min = max($minArray);
If I get the OPs question right
PHP has max and min methods specifically for this
$max = max($array); // 7.8
$min = min($array); // -14.6
//$dd = array(-50, -25, -5, -80, -40, -152, -45, -28, -455, -100, -98, -455);
$dd = array(50, -25, -5, 80, -40, -152, -45, 28, -455, 100, 98, -455);
//$dd = array(50, 25, 5, 80, 40, 152, 45, 28, 455, 100, 98, 455);
$curr = '';
$max = $dd[0];
for($i = 0; $i < count($dd); $i++) {
$curr = $dd[$i];
if($curr >= $max) {
$max = $curr;
}
}
echo "greatest number is $max";
Just do:
$max = max($array);
$min = min($array);
Much easier! ;)
I have the following:
Array
(
[0] => Array
(
[department] => Central>ACME>BusDev
[Total_Staff] => 4
[Total_Resp] => 0
)
)
There are over 150 of these within the array.
I can easily sum, for example, Total_Staff and Total_Resp using something like:
foreach($arr as $num => $values) {
$sum_staff += $values[ 'Total_Staff' ];
$sum_resp += $values[ 'Total_Resp' ];
}
However what I need to do is sum only elements of the array, for example I need to sum Total_Staff and Total_resp that lies between indexes 0 and 7 or 12 and 58.
Not sure how to go about this.
Is this what you need
foreach($arr as $num => $values) {
if(($num >= 0 && $num <= 7) || ($num >= 12 && $num <= 58))
$sum += $values[ 'Total_Staff' ];
}
Using a for loop would be the way to solve this:
$start = 12;
$end = 58;
$sum_total_staff = 0;
$sum_total_resp = 0;
for( $i = $start; $i <= $end; $i++ ) {
$sum_total_staff += $arr[$i]["Total_Staff"];
$sum_total_resp += $arr[$i]["Total_Resp"];
}
Id say use these 2 function to slice & merge the arrays. It will get 8 arrays from which are between indexes 0-7 (with 0 and 7 included) and same with the second one. If you want without 0 and 7, it would be with arguments 1, 6, so array_slide($arr, 1, 6); and so on.
$new_arr1 = array_slice($arr, 0, 8);
$new_arr2 = array_slice($arr, 12, 47);
$arr = array_merge($new_arr1, $new_arr2);