Is it possible to increment a php variable inside a foreach? I know how to loop by declaring outside.
I'm looking for something like the syntax below
foreach ($some as $somekey=>$someval; $i++)
{
}
Is it possible to increment a php variable inside a foreach? I know how to loop by declaring outside.
I'm looking for something like the syntax below
foreach ($some as $somekey=>$someval; $i++)
{
}
No, you will have to use
$i = 0;
foreach ($some as $somekey=>$someval) {
//xyz
$i++;
}
lazy way of doing is:
{
$i=1;
foreach( $rows as $row){
$i+=1;
}
}
,but you have to scope foreach for $i to dont exist after foreach or at last unset it
$i=1;
foreach( $rows as $row){
$i+=1;
}
unset($i);
, but you should use for cycle for that as leopold wrote.
$dataArray = array();
$i = 0;
foreach($_POST as $key => $data) {
if (!empty($data['features'])) {
$dataArray[$i]['feature'] = $data['features'];
$dataArray[$i]['top_id'] = $data['top_id'];
$dataArray[$i]['pro_id'] = $data['pro_id'];
}
$i++;
}
I know it is an old one here, but these are my thoughts to it.
$some = ['foo', 'bar'];
for($i = 0; $i < count($some); $i++){
echo $some[$i];
}
-- Update --
$some = ['foo', 'bar'];
$someCounted = count($some);
for($i = 0; $i < $someCounted; $i++){
echo $some[$i];
}
It would achieve, what you are looking for in first place.
Yet you'd have to increment your index $i.
So it would not save you any typing.
Is there any reason not to use
foreach ($some as $somekey=>$someval)
{
$i++;
}
?
foreach ($some as $somekey=>$someval)
{
$i++;
}
i is just a variable. Even though it's used to iterate over whatever item you're using, it can still be modified like any other.
This will do the trick! Remember that you'll have to define $i = 0 before the foreach loop if you want to start counting/incrementing from 0.
$i = 0;
foreach ($some as $somekey=>$someval) {
$i++;
}
Unfortunately, this is not possible. I was looking for an elegant way to do this, very similar to this:
for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
This works for the for
functionality in PHP, but then you would have to pull the item, such as $columns[$k]
, and then you're back to a less than ideal situation.