PHP - foreach increment more than 1 - php

I have foreach loop in which I need to assign coordinates after certain steps. For this example $n+4 (174,178,182,...).
I know that solve multiple entering n++.
$n = 174;
foreach($items as $item){
echo $item . ' coor: ' . $n . '<br>';
$n++;
$n++;
$n++;
$n++;
}
I wonder if it can not be solved more elegantly.

You can use:
$n += 4;
When you put an operator before =, it creates an operator that combines the original value of the target with the source using that operation, so that's equivalent to:
$n = $n + 4;
Similarly, if you write:
$n *= 10;
it's the same as
$n = $n * 10;

#Barmar 's solution and explanation is correct and solves your issue. But here is an alternative way you could write that code which you may find helpful:
$n = 174;
foreach($items as $i => $item){
echo $item . ' coor: ' . $n + $i*4 . '<br>';
}
Note this will only work if your array keys are numeric and incrementing. If they're not then you just need to change $items in the foreach to array_values($items).

Related

PHP, array count, two foreach combination

I am solving this not understandable script, I even don't know where from to start. Maybe someone will help me.
I got two arrays example:
$a1 = array(1,2,3 ...);
$a2 = array(4,5,6 ...);
what I need is that first array will divide all values by itsel
for this I would like to get script which will work like this (array values can be savet to the same name because will be anyway continue with them, can be new variable, in this example I use new). In the same way variable can be devidet by itself to get 1 but prefer not to. Example of count.
$b1 = array([0]/[1], [0]/[2], [0]/[3], [1]/[0], [1]/[2], [1]/[3], [2]/[0], [2]/[1], [2]/[3], [3]/[0], [3]/[1], [3]/[2]);
$b2 = array( *** The same like $b1 ***);
On the end will go foreach to write values to table, this I solved already
echo "<table><tr>";
foreach($b1 as $key1 => $val1){
foreach($b2 as $key2 =>$val2){
echo "<td>".$key1.$key2."<br/>".val1*val2."</td>";
}
echo "</tr><tr>";
}
echo "</tr></table>"
Anyone can give me a help to this issue?
To do the division of each element is relatively simple. You do it with 2 for loops. The one thing you have to bear in mind, however, is avoiding division by 0. Do you have elements that could be 0? If so, do you want the division result to be 0, or the same as the numerator? the code I show below assumes the latter:
function getDivided($array) {
$length = count($array);
$return = [];
for ($i = 0; $i < $length; $i++) {
for ($j = 0; $j < $length; $j++) {
if ($i === $j) continue;
//the following assumes that the values in the array are never < 1 Change this according to your needs
$return[] = $array[$i] / max($array[$j], 1);
//Another option is to use a conditional
$return[] = $array[$j] === 0 ? $array[$i] : $array[$i] / $array[$j];
}
}
return $return;
}
$b1 = getDivided($a1);
$b2 = getDivided($a2);

use variable name in code processing php like $number01 use it value, not name

so better will be example (so hard to give a title to this problem)
imagine I have variables in php like
$number1 = 10;
$number2 = 30;
$number3 = 23;
.. and so on..
and I just want to make an arithmetic average but not like
($number1 + $number2 +$number3)/3 because it is so much typing (having more than only 3 numbers)
but use something like
$temp=0;
for ($i=1;$i<50;$i++){
$temp=$temp+$number."$i"; <- this is what I don't know how to define..
}
and similar, how to echo all values for numbers like
for ($i=1;$i<50;$i++){
echo $number.$i; <- but this is not working..
}
I hope I have described it good, thank you for your help!
It can be done with variable variables but it's ugly:
$temp=0;
for ($i=1;$i<50;$i++){
$temp=$temp+(${$number.$i});
}
There is a limitation with the variable variables which is you don't know how high the number goes. You would also need to check if the variable is set first. A better solution is to store each of the variables in an array, which you can easily iterate over:
$arr = array();
$arr[] = 10;
$arr[] = 30;
$arr[] = 23;
$temp = 0;
foreach($arr as $val)
{
$temp += $val;
}
$number = array(10,20,30);
echo array_sum($number);
the other solution doing the same with for loop
$number = array(10,20,30);
$count = count($number);
$sum = 0;
for($i = 0; $i < $count ; ++$i) $sum += $number[$i];
or foreach
$number = array(10,20,30);
$count = count($number);
$sum = 0;
foreach($number as $n) $sum += $n;
there are a lot of methods to add items to array for example
$number = array(10,20,30);
$number = array();
$number[] = 10; $number[] = 20; $number[] = 30;
$number[0]= 10; $number[1] = 20; $number[2] = 30;
$number = array();
array_push($number, 10, 20, 30);
But the most simple and working solution is to use arrays and array_sum() function.
Array sum - Calculate the sum of values in an array
It's probably better to put all these values into an array instead of different variables. This makes adding later easier and allows you to loop like:
foreach($myArray as $number){
echo $number;
}
If you still want/need to use variables you can use variable variables:
$temp=0;
for ($i=1;$i<50;$i++){
$numberName = "number".$i;
$temp=$temp + $$numberName;//Note the $$ syntax.
}
$$foo will be the value of the variable with the name stored in $foo.
A final note. Be careful with variable variables, as they can lead to messy or unreadable code.
use an array
$number[0] = 10;
$number[1] = 20;
$number[2] = 23;
for ($i=1;$i<count($number);$i++) {
echo $number[$i]; //now this works.
}

putting a foreach inside foreach

I'm trying to loop some array using foreach.
This is the code which demonstrates what I'm doing:
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-".$key2."-".$val2;
}
}
However, this outputs
32-0-5
32-1-3
32-2-2
32-3-1
and I want to display it like this instead
32-1-5
45-2-3
67-3-2
89-3-1
How can I solve this? Since I'm a beginner I don't know what to do.
You don't want to loop over the 2nd array, you just want to get the value at a certain position. Try it like this:
foreach($arr1 as $key => $val){
$val2 = $arr2[$key];
echo $val."-".($key+1)."-".$val2;
}
I assume you're doing a double foreach because you actually want to print 4*4 = 16 rows. I also assume that you mistyped the last row, where you have a 3 instead of a 4.
Just using ($key2+1) can be enough for you ?
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-" . ($key2+1) . "-".$val2;
}
}
Do not nest the loops;
Use one loop and print array1[i]."-".array2[i]
You can use for loop instead of foreach too:
$arr1=array(32,45,67,89);
$arr2=array(5,3,2,1);
for ($i = 0; $i < 4; $i++) {
echo $arr1[$i] . "-" . ($i+1) . "-" . $arr2[$i];
}
$i<count ($arr1) counts the number of elements in the array.
And then stop once it gets to the end.
If you have the name number of elements in each array. This would be great for you or even to create tables dynamically.
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
for ($i=0; $i<count ($arr1) ; $i++){
echo $arr1[$i] . "-" . $arr1[$i]."-". $arr2[$i] ;
}

How to count order number of values in an array?

I have an array with a few values and want to do something like this:
$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $arrayvalue ) :
printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');
endforeach;
I want to have in $countvalue the number of the value in the array
ie... the array will be something like this: ("apple", "orange", "grapefruit")
I want the number to match the order number of these values
apple = 1, orange = 2, grapefruit = 3
or actually even if it's just an incremental number according to the values echoed it doesn't matter, I just need to insert a css class represented by an incremembtal number
I tried playing $i... count... but I don't know how to achieve what I want; I'm more a designer than a coder, I looked in the PHP help but couldn't find a clear solution for my case
thank you
You already have an incremental number based on order. Keep in mind, this only works if your key's are 0-based. If you use an associative array you will need to use a for loop instead (as suggested by nickb).
$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $key => $arrayvalue ){
echo "<li class='$key'>$arrayvalue</li>";
}
$arrayvalues = array_reverse(explode(', ', somefunction()));
$i = 0;
foreach ( $arrayvalues as $arrayvalue )
{
$i++;
printf('<li class="'.$i.'">'.$arrayvalue.'</li>');
}
Use a for loop to iterate over your array, like so:
for( $i = 0, $j = count( $arrayvalues); $i < $j; $i++) :
printf('<li class="' . ($i + 1) . '">' . $arrayvalues[$i] . '</li>');
endfor;
If you want the index $i to start at one, you need to add one in the printf statement.
Side note: You don't need printf here if you're not actually generating formatted output.
$arrayvalues = array_reverse(explode(', ', somefunction()));
$i=0;
foreach ( $arrayvalues as $arrayvalue ) :
++$i;
$countvalue = $i;
printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');
endforeach;
We (or I) advise you use a normal for loop.
for($i = 0; $i < count($arrayvalues); $i++) {
printf('<li class="'.($i+1).'">'.$arrayvalue.'</li>');
}

Possible to access PHP parse_str array values by index?

Hopefully this is a simple answer or doable in some other way. I want to use parse_str to store my querystring values in an array.
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
Accessing the data by name works correctly:
echo $fields['value3'];
... but accessing via index does not:
echo $fields[2];
The reason I want to access by index instead of name is because after the 2nd array value, the rest of the querystring parameters will be DYNAMICALLY generated. In other words, for the processing I'm doing -- I want to get all parameters AFTER the 2nd one. To do that, I was going to use a simple FOR loop starting from the 3rd value in the array to the sizeof(myArray);.
Any ideas how I can accomplish this?
You have to generate an indexed array then. You could for example use:
$indexed = array_values($fields);
print $indexed[2]; // eqivalent to $fields["value3"];
Note that the index starts from 0.
If you want you could also combine the named array with the indexed version:
$fields = array_merge($fields, array_values($fields));
$fields[2] == $fields["value3"];
$i = 0;
foreach ($fields as $key => $value) {
$fields[$i] = $value; //or just put your code here, and use $i
$i++;
}
for ($j = 2; $j < $i; $j++) {
//do something with $fields[$j]
}
Here:
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
$arr = array_slice($fields, 2, count($fields), true);
foreach($arr as $key=>$value) {
echo $key . "=>" . $value;
}
Just concatenate a string with an integer:
echo $fields["value" . $myInteger + 1];
where myInteger is your value (for loop, etc.). You need to add 1 because your strings are one-based.
Example:
for ($i = 2; $i < sizeof($myArray); $i++)
{
echo $fields["value" . $i + 1];
}

Categories