Reputation: 49
OK, this is weird. I have an array of time blocks:
$time_block = array("09:00:00-13:00:00","10:00:00-14:00:00");
And I want to loop through them to create a start time and end time for each block:
foreach($time_block as $val)
{
for($x = 0; $x < count($time_block); $x++)
{
$time=$val[$x];
echo substr($time,0,8);
echo "<br>";
echo substr($time,-8);
}
echo "<br>";
echo "<br>";
}
The end result should be:
09:00:00
13:00:00
10:00:00
14:00:00
But I am getting:
0
09
9
1
10
0
Any thoughts?
Upvotes: 1
Views: 77
Reputation: 78721
The problem with your approach is you're trying to loop through the element two times. If you use foreach($time_block as $val)
, in every iteration $val
will be a single element of the array. For example, on the first run, it will store "09:00:00-13:00:00"
. So in your for
loop, you were trying to loop through this $val
, which is actually possible as strings can be accessed as arrays (the characters in the string being the elements).
This will produce the exact output you needed:
foreach($time_block as $val) {
$t=explode('-', $val);
echo $t[0]."<br>".$t[1]."<br><br>";
}
Here, explode()
is used to separate the time values in $val
based on the -
character. $t
will be an array, holding the two times in $val
as its two elements.
Upvotes: 1
Reputation: 785406
In your code you are double looping, just use it like this:
$time_block = array("09:00:00-13:00:00","10:00:00-14:00:00");
foreach($time_block as $time) {
echo substr($time,0,8) . " ";
echo substr($time,-8) . "\n";
}
09:00:00 13:00:00
10:00:00 14:00:00
Upvotes: 0
Reputation: 5115
You wrote: $time = $val[$x];
$val
is not an array, it's a string, and seems like you are doing a foreach
and then a for
on the same array?
You can use something like:
foreach ($timeblock as $timeString) {
list($start, $end) = explode("-", $timeString);
echo "$start $end\n";
}
Upvotes: 3
Reputation: 44346
Try this:
for($x = 0; $x < count($time_block); $x++){
$time = $time_block[$x];
echo substr($time,0,8);
echo "<br>";
echo substr($time,-8);
echo "<br><br>";
}
You're using 2 nested loops while you only have 1 dimension in your data set. That should make you think.
Upvotes: 2
Reputation: 6570
In your foreach
loop, $val
is a string. When you ask for $val[$x]
, your asking for the xth character of that string. Probably not what you want.
Solution:
Take out the for
statement, and change
$time=$val[$x];
to
$time=$val;
Upvotes: 2
Reputation: 48131
foreach($time_block as $v) {
print_r(explode( '-',$v ));
echo '<br><br>';
}
Upvotes: 2