Is There a Function to Make a Copy of a PHP Array to Another

Is there a function to make a copy of a PHP array to another?

In PHP, all variables except objects are assigned by the mechanism called copy-on-write, while objects are assigned by reference. Which means that for the arrays with scalar values simply $b = $a already will give you a copy:

$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);

Will yield:

array(0) {
}

Whereas with objects,

$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);

Yields:

object(stdClass)#1 (1) {
["foo"]=>
int(42)
}

An edge case when array elements could be objects that need to be cloned as well, is explained in another answer

You could get confused by intricacies such as ArrayObject, which is an object that acts exactly like an array. Being an object however, it has reference semantics.

Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.

How to clone an array of objects in PHP?

References to the same objects already get copied when you copy the array. But it sounds like you want to shallow-copy deep-copy the objects being referenced in the first array when you create the second array, so you get two arrays of distinct but similar objects.

The most intuitive way I can come up with right now is a loop; there may be simpler or more elegant solutions out there:

$new = array();

foreach ($old as $k => $v) {
$new[$k] = clone $v;
}

How copy value of Php array variable to another array

I didnt rly understand what your actual problem is, but it seems like you want to merge 2 arrays together. Then you should take a look at array_merge()

http://php.net/manual/en/function.array-merge.php

$av = array(1, 2, 3, 4, 5);
$var = array("a", "b", "c", "d");
$output = array_merge($av, $var);
print_r($output);

Output:

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => a
[6] => b
[7] => c
[8] => d
)

How to copy array keys to another array, and replace values with empty array?

Try this . You can use array_fill_keys() for more info follow this link

$arr = array(
4 => 'some value 1',
7 => 'some value 2',
9 => 'some value 3',
12 => 'some value 4',
13 => 'some value 5',
27 => 'some value 6',
41 => 'some value 7'
);
$keys=array_keys($arr);

$filledArray=array_fill_keys($keys,array());
print_r($filledArray);

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

For the second part of your question, see the array page of the manual, which states (quoting) :

Array assignment always involves value
copying. Use the reference operator to
copy an array by reference.

And the given example :

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


For the first part, the best way to be sure is to try ;-)

Consider this example of code :

function my_func($a) {
$a[] = 30;
}

$arr = array(10, 20);
my_func($arr);
var_dump($arr);

It'll give this output :

array
0 => int 10
1 => int 20

Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.

If you want it passed by reference, you'll have to modify the function, this way :

function my_func(& $a) {
$a[] = 30;
}

And the output will become :

array
0 => int 10
1 => int 20
2 => int 30

As, this time, the array has been passed "by reference".


Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)

Copy array key into another existing array key

You can use the function array_combine() to combine the keys from the second array (for the following example called $array_keys) with the values from the first array (called $array_values):

Example:

$combined = array_combine(array_keys($array_keys), $array_values);
print_r($combined);

This prints out the array exactly like you described.

php copying array elements by value, not by reference

You can take advantage of the fact that PHP will dereference the results of a function call.

Here's some example code I whipped up:

$x = 'x';
$y = 'y';
$arr = array(&$x,&$y);
print_r($arr);

echo "<br/>";
$arr2 = $arr;
$arr2[0] = 'zzz';
print_r($arr);
print_r($arr2);

echo "<br/>";
$arr2 = array_flip(array_flip($arr));
$arr2[0] = '123';
print_r($arr);
print_r($arr2);

The results look like this:


Array ( [0] => x [1] => y )
Array ( [0] => zzz [1] => y ) Array ( [0] => zzz [1] => y )
Array ( [0] => zzz [1] => y ) Array ( [0] => 123 [1] => y )

You can see that the results of using array_flip() during the assigment of $arr to $arr2 results in differences in the subsequent changes to $arr2, as the array_flip() calls forces a dereference.

It doesn't seem terribly efficient, but it might work for you if $this->x->getResults() is returning an array:

$data['x'] = array_flip(array_flip($this->x->getResults()));
$data['y'] = $data['x'];

See this (unanswered) thread for another example.

If everything in your returned array is an object however, then the only way to copy an object is to use clone(), and you would have to iterate through $data['x'] and clone each element into $data['y'].

Example:

$data['x'] = $this->x->getResults();
$data['y'] = array();
foreach($data['x'] as $key => $obj) {
$data['y'][$key] = clone $obj;
}

PHP array copy certain keys, built-in functions? Nested loop performance?

I worked it out - I almost had it above.I thought I'd post the answer anyway for completeness. Hope this helps someone out!

array_intersect_key($data, array_flip($keys_to_copy))

Use array_flip() to switch $keys_to_copy so it can be used within array_intersect_keys()

I'll run some tests to compare performance between the manual loop above, to this answer. I would expect the built-in functions to be faster but they might be pretty equal. I know arrays are heavily optimised so I'm sure it will be close.

EDIT:
I have run some benchmarks using PHP CLI to compare the foreach() code in my question with the code in my answer above. The results are quite astounding.

Here's the code I used to benchmark, which I think is valid:

<?php
ini_set('max_execution_time', 0);//NOT NEEDED FOR CLI

// BUILD RANDOM DATA ARRAY
$data = array();
while ( count($data) <= 200000) {
$data[rand(0, 500000)] = rand(0, 500000);
}
$keys_to_copy = array_rand($data, 100000);

// FOREACH
$timer_start = microtime(TRUE);
foreach ($data as $key => $value) {
if ( in_array($key, $keys_to_copy)) {
$copied_data[$key] = $value;
}
}
echo 'foreach: '.(microtime(TRUE) - $timer_start)."s\r\n";

// BUILT-IN ARRAY FUNCTIONS
$timer_start = microtime(TRUE);
$copied_data = array_intersect_key($data, array_flip($keys_to_copy));
echo 'built-in: '.(microtime(TRUE) - $timer_start)."s\r\n";
?>

And the results...

foreach: 662.217s

array_intersect_key: 0.099s

So it's much faster over loads of array elements to use the PHP array functions rather than foreach. I thought it would be faster but not by that much!

Is there to validate json objects with another array of json in php

Doesn't look that bad. However, only one loop is required:

public function dataValidator($data)
{
foreach($data as $key => $value) {
$valid = current(array_filter($formDefinition, function($form) use($key) { return $form->key === $key; }));
if(!$valid) {
return 'invalid';
}
}
}

Short tip for next time: Just try it out. That might avoid unnecessary questions since you might already get the answers from the result. And if not, you at least have sufficient debugging information to share with us ;-)



Related Topics



Leave a reply



Submit