Reputation:
Okay below I have attached my code, I'm trying to use the $current_statement
and $next_statement
to define the values in the array. the $current_statement
is = to 7 and the $next_statement
is = to 8. What I'm trying to do is define the 7th and 8th value in the array from the using the two values from $current_statement
and $next_statement
.
<?
$date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14','16-03-28',
'16-04-14','16-04-28','16-05-14','16-05-28','16-06-14','16-06-28','16-07-14',
'16-07-28','16-08-14','16-08-28','16-09-14','16-09-28','16-10-14','16-10-28',
'16-11-14','16-11-28','16-12-14','16-12-28');
$currentdate = date('y-m-d');
foreach ($date as $i => $d) {
if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
$current_statement = $i;
$next_statement = $i+1;
}
}
?>
Example
I'm trying to use the two numeric values from the $current_statement
and the $next_statement
to select the value from the array. So for example if the $current_statement
was = to 7 it would select the 7th value from the array and define it as a separate variable. And if the $next_statement
was = to 8 it would select the 8th value from the array and define it as a separate variable. So I could easily echo out both variables.
Upvotes: 0
Views: 69
Reputation: 1372
I think you need to prevent the index out of bound exception:
$current_statement = false;
$next_statement = false;
foreach ($date as $i => $d)
{
if ($id<count($date)-1 && ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])))
{
$current_statement = $i;
$next_statement = $i+1;
}
}
if($current_statement)
{
$current_date = $date[$current_statement];
$next_date = $date[$next_statement];
}
And shortly, if you don´t need the $current_statement and $next_statement variables more:
foreach ($date as $i => $d)
{
if ($id<count($date)-1 && ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])))
{
$current_date = $date[$i];
$next_date = $date[$i + 1];
}
}
Forget this answer
You are preventing with this clausure: $i == count($date)-1
Upvotes: 0
Reputation: 94672
I am not totally clear on your requirement, so this answer is a bit of a guess, which of course I should not really do. But do you mean something like this
<?php
$date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14',
'16-03-28','16-04-14','16-04-28','16-05-14','16-05-28',
'16-06-14','16-06-28','16-07-14', '16-07-28','16-08-14',
'16-08-28','16-09-14','16-09-28','16-10-14','16-10-28',
'16-11-14','16-11-28','16-12-14','16-12-28');
$currentdate = date('y-m-d');
foreach ($date as $i => $d) {
if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
echo 'Current statement date = ' . $date[$i];
echo 'Next statement date = ' . $date[$i+1];
}
}
?>
In which case you do not need the 2 variables you created, you can just use $i
and $i+1
Upvotes: 2