AlxVallejo
AlxVallejo

Reputation: 3238

PHP Variables in Arrays

Ok, so here's my code:

$output = array();
$output['num_items_in_tree'] = 0;
$output['date_of_most_recent_item'] = $today;
$output['num_comments_in_tree'] = 0;
$output['date_of_most_recent_comment'] = '';
$today = the_date();
print_r( $output );

I would expect the 'date_of_most_recent_item' to have today's date but there is zero output.

Oh, how little I know...

Upvotes: 1

Views: 86

Answers (5)

Tesserex
Tesserex

Reputation: 17314

Additional point not covered yet: assuming the_date() is from Wordpress, you also have the issue of it echoing, not returning the value. The final optional argument needs to be set to false.

edit: the signature is the_date( $format, $before, $after, $echo ). To me this is pretty ugly, since $echo defaults to true, and it's last. So to return the value instead of echoing it, you need to say:

$today = the_date( "F j, Y", "", "", $echo );

since those ore the default arguments. If I designed that function I would just return always and let the user echo it if they wanted. How hard is it to write <?= the_date(); ?> instead of <? the_date(); ?>

Upvotes: 0

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

Just invert your two statements where $today is involved:

$today = the_date(); // this statement must be before you use $today
$output = array();
$output['num_items_in_tree'] = 0;
$output['date_of_most_recent_item'] = $today;
$output['num_comments_in_tree'] = 0;
$output['date_of_most_recent_comment'] = '';
print_r( $output );

Upvotes: 4

jonstjohn
jonstjohn

Reputation: 60346

Technically, you don't have to modify the order in which you are assigning variables. I believe the issue you are encountering here is one of references.

When you assign a variable with a string value in PHP, the string itself is copied. However, you can modify that behavior if you wish by assigning a reference to the variable rather than the copy of the string. You would accomplish that as follows:

$output['date_of_most_recent_item'] =& $today;
$today = the_date();

I would say that this is probably less common than re-ordering your statements, but if it is what you want to achieve, then you can do it this way.

Upvotes: 0

Matt Stauffer
Matt Stauffer

Reputation: 2762

When you set the value of $output['date_of_most_recent_item'] to be $today, $today hadn't been set yet. So, you just set it to the value of an unitialized variable--nothing.

Your best option:

$output = array();
$output['num_items_in_tree'] = 0;
$output['date_of_most_recent_item'] = the_date();
$output['num_comments_in_tree'] = 0;
$output['date_of_most_recent_comment'] = '';

print_r( $output ); 

Upvotes: 0

Ayush
Ayush

Reputation: 42450

$output['date_of_most_recent_item'] = $today;

At this point, $today is uninitialized, and hence date_of_most_recent_item holds no value.

You assign a value to $today later.

Upvotes: 0

Related Questions