How to print keys and values ​​in an array
P粉204079743
P粉204079743 2023-08-06 14:18:22
0
2
402
<p>I'm trying to format my array like this: Name is John, Age is 30. Here is my sample array and code: </p> <pre class="brush:php;toolbar:false;">$user = array( 'name' => 'John', 'age' => 35 ); echo key($user)." is ".($user[key($user)]).","; // prints "name is John,"</pre> <p>If there are no more results to print, the comma (,) will disappear. <br /><br />I'm not very good at logic, but can you help me? This will be a big help! Thank you in advance. </p><p><br /></p>
P粉204079743
P粉204079743

reply all(2)
P粉310931198
$user = array(
    'name' => 'John',
    'age' => 35
);

// echo key($user)." is ".($user[key($user)]).",";

$counter = count($user);
$i = 1;
$res = '';

foreach ($user as $key => $value) {
    $res .= $key. " is ". $value;
    if ($counter != $i) {
        $res = $res .", ";
    }
    $i = $i + 1;
}
echo $res;
P粉826429907
$values =[];

foreach ($user as $key => $value) {
    $values[] = "{$key} is {$value}";
}
echo implode(', ', $values);

or

$values = array_map(fn($key, $value) => "{$key} is {$value}", array_keys($user), $user);
echo implode(', ', $values);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!