Display array values in PHP

2019-01-08 22:07发布

So, I'm working with PHP for the first time and I am trying to retrieve and display the values of an array. After a lot of googling, the only methods I can find for this are print_r, var_dump or var_export. However, all of these methods return something that looks like this:

[a] => apple
[b] => banana
[c] => orange

I can't figure out how to style this outout. I need to strip away the [a] => part and add commas. I know this must be a pretty straightforward process but I haven't been able to track down any documentation that demonstrates how to do it.

8条回答
手持菜刀,她持情操
2楼-- · 2019-01-08 22:08

Iterate over the array and do whatever you want with the individual values.

foreach ($array as $key => $value) {
    echo $key . ' contains ' . $value . '<br/>';
}
查看更多
小情绪 Triste *
3楼-- · 2019-01-08 22:12

You can use implode to return your array with a string separator.

$withComma = implode(",", $array);

echo $withComma;
// Will display apple,banana,orange
查看更多
女痞
4楼-- · 2019-01-08 22:13

you can easily use join()

$fruits = array("apple", "banana", "orange");
print join(" ".$fruits);
查看更多
贪生不怕死
5楼-- · 2019-01-08 22:23
<?php $data = array('a'=>'apple','b'=>'banana','c'=>'orange');?>
<pre><?php print_r($data); ?></pre>

Result:
Array
(
          [a] => apple
          [b] => banana
          [c] => orange
)

查看更多
叼着烟拽天下
6楼-- · 2019-01-08 22:23

a simple code snippet that i prepared, hope it will be usefull for you;

$ages = array("Kerem"=>"35","Ahmet"=>"65","Talip"=>"62","Kamil"=>"60");

reset($ages);

for ($i=0; $i < count($ages); $i++){
echo "Key : " . key($ages) . " Value : " . current($ages) . "<br>";
next($ages);
}
reset($ages);
查看更多
趁早两清
7楼-- · 2019-01-08 22:28

the join() function must work for you:

$array = array('apple','banana','ananas');
$string = join(',', $array);
echo $string;

Output :

apple,banana,ananas

查看更多
登录 后发表回答