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?
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.
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).
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.
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
You need to write yourself a function for that. PHP has get_object_vars
Docs 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With