Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – dynamically assign values to key in array

I have two array values:

$values = ["Phillip", "Phil"];

In my set() method, I want to return an array object that first has a defined name key and second nickname key, like:

array(2) {
  "name" => "Phillip"
  "nickname" => "Phil"
}

Is there a better way to do it? I am new at PHP, though.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function set(?array $values)
{
    $items = [];
    foreach ($values as &$item) {
        $item['name']     = $items;
        $item['nickname'] = $items;
    }
}

>Solution :

Like this

<?php

$values = ["Phillip", "Phil"];

function set(array $values): array
{
        return [ "name" => $values[0], "nickname" => $values[1] ];
}

var_dump(set($values));

Result

array(2) {
  ["name"]=>
  string(7) "Phillip"
  ["nickname"]=>
  string(4) "Phil"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading