Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fill an object in PHP from an Array

Tags:

php

Suppose I have:

class A{
 public $one;
 public $two;
}

and an array with values:

array('one' => 234, 'two' => 2)

is there a way to have an instance of A filled with the right values from the array automatically?

like image 908
gotch4 Avatar asked Mar 06 '12 15:03

gotch4


People also ask

How to fill an array with values in PHP?

The array_fill () function is used to fill an array with values. The function fills an array with num entries of the value of the array_values parameter, keys starting at the starting_index parameter. array_fill (starting_index, num_of_elements, array_values ) The first index of the returned array. Allows non-negative indexes only.

How can I add an object to an array in PHP?

In PHP, how can I add an object element to an array? This will produce the following output − Suppose myArray already contains ‘a’ and ‘c’, the value of “My name” will be added to it. It becomes Array { a:0, c:1, “My name”:2 } The object is created and then it is pushed to the end of the array (that was previously present).

How do you fill an array with Count entries?

Fills an array with count entries of the value of the value parameter, keys starting at the start_index parameter. The first index of the returned array. If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero (see example ). Number of elements to insert.

How to get the length of an array in PHP?

PHP Arrays 1 Create an Array in PHP 2 Get The Length of an Array - The count () Function 3 Complete PHP Array Reference. For a complete reference of all array functions, go to our complete PHP Array Reference. ... 4 PHP Exercises


1 Answers

You need to write yourself a function for that. PHP has get_object_varsDocs but no set counterpart:

function set_object_vars($object, array $vars) {
    $has = get_object_vars($object);
    foreach ($has as $name => $oldValue) {
        $object->$name = isset($vars[$name]) ? $vars[$name] : NULL;
    }
}

Usage:

$a = new A();
$vars = array('one' => 234, 'two' => 2);
set_object_vars($a, $vars);
like image 177
hakre Avatar answered Oct 31 '22 09:10

hakre