0

I have the following array:

$fields = ['field1', 'field2', 'field3'];

What I would like to do using an existing helper ('hopefully') is to convert those array string values into object key value pairs with an empty value.

This is the desired output:

  $fields = (object) [
    'field1' => '',
    'field2' => '',
    'field3' => '',

  ];

Is it possible to do that using a Laravel helper, so I don't have to use my own function?

  • 1
    Does this answer your question? [How to convert an array to object in PHP?](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) – Jeremy Layson Apr 25 '21 at 15:25
  • 1
    In addition to the above duplicate, just do `$fields = (object)(array_fill_keys($fields, ''));` – nice_dev Apr 25 '21 at 15:26
  • I do not recommend you to do what you want to do. And with more emphasys if you are using Laravel... If you are working with OOP, you should know that everything is an "entity", there is no "standard object" in the wild, no more `stdClass`, it has to have a meaning, it must be an object that has meaning only if you want good coding practices... – matiaslauriti Apr 25 '21 at 22:34
  • So, it should be using a Mapper pattern or just send the array to the constructor of your defined object and let it do what you want it to do... You can even use Collections. – matiaslauriti Apr 25 '21 at 22:36

1 Answers1

1

You could try the following code to create a generic object.

$obj = new \stdClass();

foreach ($fields as $field) {
    $obj->$field = '';
}

The reason this works is that it will iterate over each field, add set properties on the object, using the value of the array.

Note the ->$ symbol. This is because PHP will solve the $ into the value of the variable, then it will set that as the property after the arrow.


If you were to use an associative array, then you could take this a step further.

$fields = ['field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3'];

foreach ($fields as $field => $value) {
    $obj->$field = $value;
}
JustCarty
  • 3,839
  • 5
  • 31
  • 51