Increment number by 1 in foreach loop upto 10 - php

I am trying to increment a value in a foreach loop, but I need it to be maximum 10. How can I do that? My current code is
$i = 0;
foreach ( $signatures as $signature ) {
echo 'Signature ID: ' . $signature . $i;
$i++;
}
Where this foreach loop should stop when the value of $i should reach 10.
Thanks

This would do it.
$i = 0;
foreach ( $signatures as $signature ) {
if($i==10){
break;
}
echo 'Signature ID: ' . $signature . $i;
$i++;
}
Just use break if you want to end any iteration.

Along with breaking the foreach loop at 10, you could just do a for loop:
If $signatures is a numerical array:
for($i = 0; $i < 10; $i++) {
$signature = $signatures[$i];
}
If $signatures is an associative array, access with current() and advance with next():
for($i = 0; $i < 10; $i++) {
$signature = current($signatures);
next($signatures);
}

Related

Calculate sum in while loop to array

When the number 6 is giving I need to calculate till 6: for example: 1+2+3+4+5+6=21. I also need to add the sums of each to an array like: 1+2=3, 1+2+3=6, 1+2+3+4=10, ...
I have tried to make the while loop to be printed and this working fine but nog for array purpose:
<?php
$number = $_POST['number'];
$i = 1;
$cal = 0;
$tussenBerekening = array();
while ($i <= $number) {
echo $i;
$cal = $cal + $i;
array_push($tussenBerekening, $cal);
if ($i != $number) {
echo " + ";
} else {
echo " = " . $cal;
}
$i++;
}
?>
This is my new code, it prints, but no total sum.
<?php
$number = $_POST['number'];
$i = 2;
$cal = 0;
$sum = 1;
$berekeningen = array();
while ($i <= $number) {
$sum .= "+" . $i;
array_push($berekeningen, $sum);
$i++;
}
print_r($berekeningen);
?>
Here's a solution:
$i = 1;
$number = 6;
while ($i <= $number) {
// generate array with values from 1 to $i
$array = range(1, $i);
// if there're more than 1 element in array - output sum
if (count($array) > 1) {
// 1+2+... part // sum of elements of array
echo implode('+', $array) . ' = ' . array_sum($array) . '<br />';
}
$i++;
}

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

How can I sum up values from a json string?

I get the following json data from a database:
[{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}][{"type":"Sig","value":"0.0"},{"type":"SH","value":"9.95"},{"type":"COD","value":"6.95"}]
I'm trying to add all value values together, so: 9.95 + 6.95 ... so that I get 67.6 as result.
I tried the below code, but I am getting 16.9 as repeated values.
for ($i = 0; $i <= $count - 1 ; $i++) {
$charge = $service[$i]['charge'];
$serviceValue = json_decode($charge, true);
$totalservice = 0;
foreach ($serviceValue as $key => $value) {
$totalservice += $value['service_value'];
}
echo $totalservice;
}
You can do it like below:-
$jsonObj = json_decode($json); // Decode the JSON to OBJ
// Now loop and find the SUM
$total = 0;
foreach ($jsonObj as $item){
$total =+ $item->value;
}
// Print the SUM
echo "Sum : $total";
Note:- In your code $totalservice beome 0 every time when loop goes to next iteration and that's why you are getting same value repeated time. So do like (what #u_mulder said) :-
$totalservice = 0;
for ($i = 0; $i <= $count-1 ; $i++) {
.....//rest code
}
I have made the below changes. It works fine.
$totalservice = 0;
for ($i = 0; $i <= $count-1 ; $i++) {
$charge = $service[$i]['charge'];
$serviceValue = json_decode($charge, true);
foreach ($serviceValue as $key => $value) {
$totalservice+= $value['service_value'];
}
echo $totalservice;
}
Thanks for the help

Replacing "foreach" with "for" in PHP

I need to replace my "foreach" with "for", but actually I don't know how.
Here is the part of my php code:
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
echo "\n\r" . $v->id . "\n\r";
if (1) {
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
Thanks!
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
echo "\n\r" . $v->id . "\n\r";
if (1) { //you don't really need this, because it's allways true
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
if $orgs is an associative array, it becomes:
$r = "";
$j = 0;
for($i = 0; $i < count($orgs); $i++)
{
echo "\n\r" . $orgs[$i]->id . "\n\r";
$a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id);
$connection = $a_view_modl->getDbConnection();
}
better you do some checks first if you go for this solution.
if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal:
$i++; //if you want the increment afterwards
++$i; //if you want the increment before you read your variable
the same for decrements:
$i--; //decrement after reading the variable
--$i; //decrement before you read the variable
$r = "";
$j = 0;
for($i = 0 ; $i < count($orgs); $i++)
{
$v = $orgs[$i];
echo "\n\r" . $v->id . "\n\r";
if (1) {
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
}
A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v.
Then $v has the value you are using in the snippet of code.
A for loop does only accept indexed arrays, and no associative arrays.
We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0.
$r = "";
$j = 0;
for ($i = 0; $i < count($orgs); $i++) {
echo "\n\r" . $orgs[$i]->id . "\n\r";
if (1) {
$a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id);
$connection = $a_view_modl->getDbConnection();
foreach ($orgs as $k => $v) {
// Your stuff
}
for loop
for ($i = 0; $i < count($orgs); $i++) {
// Your stuff ... use $orgs[$i];
}

Php nestedfor loop

I have an array in php, and I want to print the elements of the array, 15 at a time, from (n-15). Like, if I have 100 elements in an array, I want to print it 85-100,70-84,55-70,, etc.,
I've tried the loop
for( $j = sizeof($fields)-16; $j < sizeof($fields); ) {
for ( $i = $j ; $i < $i+16 ; $i++ ) {
echo $fields[$i];
echo "<br>";
}
$j=$j-16;
}
but, this prints only the first iternation, i.e 85-100, and goes into an infinite loop.
Where am i going wrong?
Help!
foreach (array_reverse(array_chunk($fields, 15)) as $chunk) {
foreach ($chunk as $field) {
echo $field . '<br />';
}
}
In PHP 5.3, you can do this:
<?php
$fields = range(1, 100);
foreach (array_chunk(array_reverse($fields, true), 15, true) as $i => $chunk) {
echo 'Group ' . $i . ":<br/>\n";
$chunk_rev = array_reverse($chunk, true);
array_walk($chunk_rev, function($value) {
echo "$value<br/>\n";
});
}
See the demo.
Think about the loop termination condition.
If $j is being decremented and $j starts off lower than the comparison value, $j will never be greater than the comparison value, so the loop will never terminate.

Categories