Monday, August 29, 2022

[FIXED] How to create comma separated list from a while-loop?

Issue

$personas = [
'Hermann' => [
  'status' => '0',
  'gender' => 'maskulin'
],
'Lida' => [
  'status' => '1',
  'gender' => 'feminin'
],
'Susi' => [
  'status' => '0',
  'gender' => 'feminin'
],
'Mara' => [
  'status' => '0',
  'gender' => 'feminin'
]
];

Personas with status 0

  echo 'Personas with status 0: ';
  while ($status = current($personas)) {
    if ($status['status'] == '0') {
    $status_list = key($personas);
    echo $status_list;

  }
  next($personas);
}

Result is: Personas with status 0: HermannSusiMara

is expected: Personas with status 0: Hermann, Susi, Mara


Solution

A bit different solution for you.

$statusZeroPersonae = [];

foreach($personas as $personaName => $persona) {
    if ($persona['status'] === '0') {
        $statusZeroPersonae[] = $personaName;
    }
}

echo 'Personae with status 0: ' . implode(", ", $statusZeroPersonae);


Answered By - MyLibary
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.