How to use the value of a variable that is declared as an array ( ending with '[ ]' )?
<?php $postid[] = get_the_ID(); // capture the id (a number) ?>
Now If I echo $postid
I just get: Arra开发者_开发知识库y
and when I do the following:
<?php
$default = array(
'posts_per_page' => $postid
);
?>
I don't get anything either.
Any suggestions?
When working with arrays in PHP, you can use the following to assign an array to a variable :
// initalize empty array
$a = array();
var_dump($a);
(The array()
could be non-empty, of course)
Or you can use the following syntax, without the indexes :
// push items at the end of the array
$a[] = 10;
$a[] = 20;
var_dump($a);
And, finally, you can set an item at a key of your choice :
// put an item at a given index
$a['test'] = 'plop';
var_dump($a);
For more informations, see the Arrays sections of the manual.
Doing so, thanks to the three var_dump()
calls, I'll get :
array
empty
array
0 => int 10
1 => int 20
array
0 => int 10
1 => int 20
'test' => string 'plop' (length=4)
Note : many use print_r()
instead of var_dump()
-- I tend to prefer var_dump()
, which displays more informations, especially when the Xdebug extension is installed.
But note that, in any case, calling echo
on an array itself :
echo $a;
Will get nothing else as output than :
Array
Which is not quite useful ;-)
Still, you can display the value of a single item of that array :
echo $a['test'];
Which, in this case, would get you this output :
plop
Basically : echo
is not what you should use when you want to display an array :
- Either use
var_dump()
if you want to inspect an array for debugging purposes, - or loop over the array with
foreach
, displaying each item with echo- Note : you might have to do some recursion, to inspect sub-arrays ;-)
精彩评论