How to use a variable in an array request in php - php

Im using
$i = 0;
while ($i <= 6) {
print $game['stats']['item0'];
$i++;
}
I want the item0 to increment to item1 up to item6, so the last while should be
print $game['stats']['item6'];
I also tried: $game['stats']['item{$i}'] but it doesn't work.
Any Ideas for me?

If you need to do something a set number of times, a for loop is generally more concise than a while loop.
for ($i=0; $i < 6; $i++) {
print $game['stats']["item$i"];
}
It isn't a more correct way of doing it, it really just depends on your style, but I thought it was worth mentioning.

You can try this:
while ($i <= 6) {
$key = 'item'.$i;
print $game['stats'][$key];
$i++;
}

You should be good to go with this
$i = 0;
while ($i <= 6) {
print $game['stats']["item$i"];
$i++;
}
When a string is specified in double quotes or with heredoc, variables
are parsed within it.

Include the $i at the end of the string :
<?php
$i = 0;
while ($i <= 6) {
print $game['stats']['item' . $i]; //<============== , 'item0', 'item1', ...
$i++;
}
?>

You have to append $i after item. And you don't need to define new variable.
$i = 0;
while ($i <= 6) {
print $game['stats']['item'.$i];
$i++;
}

Here's an edited version of your code. It should work:
<?php
$i = 1;
$game = array("stats" =>
array("item1" => 1, "item2" => 2, "item3" => 3, "item4" => 4, "item5" => 5, "item6" => 6 ));
while ($i <= 6) {
$tmp = 'item'.$i;
print $game['stats'][$tmp];
$i++;
}

Related

How to compare every value in a for loop?

I have a multidimentional array of 5 items and I want that my loop would compare it like:
1 -> 2, 1 -> 3, 1 -> 4, 1 -> 5, 2->1, 2->3, 2->4, 2->5......// so on and 5 -> 4 in the end.
The problem is that after my array $i value matches 1 and $j value matches 3, the unset is done and the $i value becomes 2 (which is correct) and $j value becomes 4 instead of 3. Could someone tell me why and what I'm doing wrong?
My loop is:
for ($i = 0; $i <= count($myArray); $i++) {
for ($j = $i+1; $j <= count($myArray); $j++) {
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
$i++;
}
}
}
I think that's the problem is when you unset the element in the array, you increment the counter of the loop $i. In this way, the elements of the array that are not configured are removed, this empty array position will be maintained, it will not be reordered, you will have to do it manually or using array_values ​​method.
In the last tour of the array, it will break because you are comparing the number of array elements as equal. You must use index < count($array)
The code would be like this:
for ($i = 0; $i < count($myArray); $i++) {
for ($j = $i+1; $j < count($myArray); $j++) {
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
// $i++;
}
}
}
try something like this
for ($i = 0; $i <= count($myArray); $i++) {
for ($j = 0; $j <= count($myArray); $j++) {
if ($j!=$i)
{
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
$i++;
}
}
}
}
$temp = $myArray;
for ($i = 0; $i <= count($myArray); $i++)
{
for ($j = $i + 1; $j <= count($myArray); $j++)
{
if (
// condition 1
&& // condition 2
)
{
unset($temp[$i]);
$i++;
}
}
}
print_r($temp);
Your result is in $temp. So here indexes wont get hampered, you actually are applying all operation on $temp and normally traversing $myArray.
To be honest, I do not know why nobody has yet advise to use nested foreach, since you all noticed there was a problem with array size.
foreach ($numbers as $number_horizontal_parsing) {
foreach ($numbers as $number_vertical_parsing) {
if ($number_horizontal_parsing != $number_vertical_parsing) {
//do your stuff in your case it seems you want to compare both variables
}
}
}

Change variable value and push it after loop

I have code like this
$jumlahcolspan = array();//new array
$horizontaldeep = 5;
$level = array(5,4,3,8,7);//old array
for ($j = 0; $j < $horizontaldeep; $j++) {
$jml = 1;
for ($i = $j + 1; $i < $horizontaldeep; $i++) {
$jml = $level[$i] * $jml;
}
array_push($jumlahcolspan, $jml);
}
To put it simple, what I want to get is to multiply old array value which index start from $i+1 to the last and push it to another array.
So, its some thing like this
old array: [5, 4, 3, 8, 7]
new array: [4*3*8*7, 3*8*7, 7, 1]
I've tried this but it doesn't work also
for ($j = 0; $j < $horizontaldeep; $j++) {
$jml = 1;
for ($i = $j + 1; $i < $horizontaldeep; $i++) {
global $jml;
$jml = $level[$i] * $jml;
}
array_push($jumlahcolspan, $jml);
}
Tried this too but not work also.
for ($j = 0; $j < $horizontaldeep; $j++) {
array_push($jumlahcolspan, array_product(array_slice($level, $j+1)));
}
Note: now I'm reviewing my full code. May be something not right in my code.
I think the problem is related to $jml variable but I can't figure how to solve that. Can anyone help me?
One approach would be to use a Recursive Function to achieve that goal. The Recursive Function below demonstrates how. And, by the way, you may as well quick-test it here.
<?php
$oldArray = [5,4,3,8,7];
function arrayMatrixMultiply(array $old, array &$newArray=[]){
$result = 1;
foreach($old as $key=>$value){
if($key != 0){
$result*=$value;
}
}
$newArray[] = $result;
array_splice($old, 0, 1);
if(!empty($old)){
// JUST RECURSE TILL THE $oldArray BECOMES EMPTY
arrayMatrixMultiply($old, $newArray);
}
return $newArray;
}
$newArray = arrayMatrixMultiply($oldArray);
var_dump($newArray);
// PRODUCES::
array (size=5)
0 => int 672
1 => int 168
2 => int 56
3 => int 7

PHP Array, Get every 4 results and output in a loop

I'm trying to output my array results in groups of 4.
<?php for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } ?>
The above does 4, but obviously doesn't re-loop.
You can loop whole array and group you output with help of "%" operator.
<div>
<?php for ($i = 0; $i < count($array); $i++) {
if (($i % 4) == 0) {
echo "</div><div>";
}
echo "Element " . $array[$i]; // CODE
}
</div>
Other than using Mod as the other answers show, you could use array_chunk() to create the groups:
$groups = array_chunk($original_array, 4);
foreach($groups as $group){
echo '<div>';
foreach($group as $item){
echo $item;
}
echo '</div>';
}
You can use a while loop to reloop for the whole results to be printed
<?php while(conditions) {
for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } } ?>
Try this that way you can jump by 4
for ($i = 0; $i < 20; $i = $i+4) {
echo $i.'<br/>';
}
I would use a foreach and then just throw in an extra check to output the divs.
$i=0;
foreach ($array as $key->$val)
{
if($i%3==0)
{
echo "<div>";
}
// your stuff
if($i%3==0)
{
echo "</div>";
}
$i++;
}
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
you can check out from here http://php.net/manual/en/function.array-slice.php
try this, use nested for loop, this will loop 4 times. You can try to integrate with your code. If
for ($i = 0; $i < 4; $i++){
for($j = 0; $j < 4; $j++){
echo $a[$j++];
}
echo "<br/>";
}
I hope it can help you.
you can try $i++, because you use ++$i in this way "for" works 3 times!
for ($i = 0; $i < 4; $i++)

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

PHP for loop - how to escape first iteration?

Given this PHP for loop
$row->frequency = 1;
$row->date_1 = 10000;
$row->interval = 86400;
for ($i = 0; $i <= $row->frequency; $i++) {
$cal_data[] = array(
'start' => strtotime($row->date_1) + $row->interval,
);
}
I would like the first iteration of the loop to ignore the + $row->interval giving me as a result:
10000
96400
I've seen this done with modulus but couldn't manage to make it work here. Anyone have suggestions?
Thanks!
Use + ($i ? $row->interval : 0)
In other words, if $i is zero - first iteration - add 0 instead of $row->interval. This is the ternary operator, (condition ? iftrue : iffalse) which is roughly equivalent to an if/else construction except it can be used amidst a statement.
for ($i = 0; $i <= $row->frequency; $i++) {
if ($i == 0) {
$val = strtotime($row->date_1) ;
} else {
$val = strtotime($row->date_1) + $row->interval;
}
$cal_data[] = array(
'start' => $val
);
}

Categories