skip to Main Content

I am trying to format my array into something like this: name is John, age is 30. Here is my sample array and code:

$user = array(
    'name' => 'John',
    'age' => 35
);

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

The comma (,) will be gone if there’s no more results to be printed out.

I am bad at logic but can you help me for this? It will be a great help! Thanks in advance.

2

Answers


  1. $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);
    
    Login or Signup to reply.
  2. $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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search