Printing Array without any loop or recursion
is there开发者_JAVA技巧 is a way to Print array without any loop or recursion in php?
print_r()
or var_dump()
You could try print_r($array); or var_dump($array); to display key/value information about the array. This is used mainly for debugging.
Alternatively if you want to display the array to users, you can use implode to stick the elements together with custom "glue", implode(' ',$array);.
print_r
is the function your looking for.
Depends on what you want.
print_r() prints human-readable information about a variable but var_dump() displays structured information about expressions that includes its type and value.
It depends on your wanted result. You could use several functions for different purposes.
Here are some examples:
You can use print_r for debug output.
<?php
$a = array ('a' => 'Apfel', 'b' => 'Banane', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
... will produce
Array
(
[a] => Apfel
[b] => Banane
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
If you need some specific formated result/output you could use array_walk
<?php
$fruits = array("d" => "Zitrone", "a" => "Orange", "b" => "Banane", "c" => "Apfel");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2<br>\n";
}
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'Frucht');
array_walk($fruits, 'test_print');
?>
... will produce
d. Zitrone
a. Orange
b. Banane
c. Apfel
d. Frucht: Zitrone
a. Frucht: Orange
b. Frucht: Banane
c. Frucht: Apfel
An even more generic way might be iterator_apply
<?php
function print_caps(Iterator $iterator) {
echo strtoupper($iterator->current()) . "\n";
return TRUE;
}
$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>
... will produce
APPLES
BANANAS
CHERRIES
But in the end... they are all loop through the array internally, of course. There are many other functions (e.g. array_map) that might be the right choice for your coding... have a look at the documentation of php and search for array functions.
function num($a,$b){
if($b<0)
{
return false;
}
else
{
echo $a * $b;
num($a,--$b);
}
}
$a=1;
$b=5;
精彩评论