Home  >  Q&A  >  body text

How to print keys and values ​​in an array

<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粉204079743P粉204079743464 days ago409

reply all(2)I'll reply

  • P粉310931198

    P粉3109311982023-08-07 11:24:14

    $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;

    reply
    0
  • P粉826429907

    P粉8264299072023-08-07 09:41:59

    $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);

    reply
    0
  • Cancelreply