Jump to content

problem with array key !


yami007

Recommended Posts

I want to store all the hours 0,1,2,3... in my $time array but it returns the last value only and I dont understand why...

<?php
$time = array();
$hour = 0;
for ( $i=0; $i<=7; $i++ ) {
$time['hour'] = $hour;
$hour++;
}
?>

Link to comment
Share on other sites

In this line:

 

$time['hour'] = $hour;

 

You're overwriting the "hour" index in the array on every iteration. I'm guessing you either just want:

 

$time[] = $hour;

 

To have a single dimension array holding the times, or:

 

$time['hour'][] = $hour;

 

If you want the hour index to be an array itself.

Link to comment
Share on other sites

You are right I wanted to do something like the latter...but I have minutes too, I want the array to be something like this

 

Array
(
[0] => Array
(
[hour] => 8
[minute] => 0
)
[1] => Array
(
[hour] => 8
[minute] => 45
)
)

 

anyway to do this ?

Link to comment
Share on other sites

You can set both at once like:

 

$time[] = array(
    'hour' => $hour,
    'minute' => $minute
);

 

But it kind of depends where you're getting the data from. Using a loop like you are doing is good for the hour, but you then need the minutes. Are you just wanting to generate an array for each hour with 0, 15, 30 and 45 minutes?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.