Link to PHP copy from array to array

Codes:

$a = array('email'=>'orange@test','topic'=>'welcome onboard','timestamp'=>'2017-10-6');

$b = array();
foreach($a as $v){
    $b[] = &$v;
}

var_dump($a);
var_dump($b);

Result:

array(3) {
  ["email"]=>
  string(11) "orange@test"
  ["topic"]=>
  string(15) "welcome onboard"
  ["timestamp"]=>
  string(9) "2017-10-6"
}
array(3) {
  [0]=>
  &string(9) "2017-10-6"
  [1]=>
  &string(9) "2017-10-6"
  [2]=>
  &string(9) "2017-10-6"
}

Why is the content of $ b not a reference to every element of $ a? What I expected from $ b should be like {& a [0], & a [1], & a [2]} instead of {& a [2], & a [2], & a [2] }

+4
source share
4 answers

Even if I had an error when I tried to reference the key

$a = array('email'=>'orange@test','topic'=>'welcome onboard','timestamp'=>'2017-10-6');

$b = array();
foreach($a as &$key=>&$v){
    $b[] = &$v;
}

Fatal error: key element cannot be a link

Can someone explain to me why you cannot pass the key as a reference?

Because the language does not support this. It will be difficult for you to find this ability in most languages, hence the key.

So am I stuck with something like this?

Yes. The best way is to create a new array with the appropriate keys.

Any alternatives?

- . , , SQL.

Re: :

<?php

$a = array('email'=>'orange@test','topic'=>'welcome onboard','timestamp'=>'2017-10-6');

$b = array();
foreach($a as $key=>&$v){
    $b[] = &$v;
}
echo "<pre>";
print_r($a);
echo "</pre>";echo "<pre>";
print_r($b);

Array
(
    [email] => orange@test
    [topic] => welcome onboard
    [timestamp] => 2017-10-6
)
Array
(
    [0] => orange@test
    [1] => welcome onboard
    [2] => 2017-10-6
)
+3

foreach, $b $v. foreach / $v, "2017-10-6".

$a :

foreach($a as $k => $var){
    $b[] = &$a[$k];
}
+2

 foreach($a as &$v){
      $b[] = &$v;
 }

Live demo: https://eval.in/875570

$a["email"] = "test"; , $b

Live demo: https://eval.in/875571

0

. b. .

<?php
$a =   
array('email'=>'orange@test','topic'=>'welcome
onboard','timestamp'=>'2017-10-6');
$b = array();
 foreach($a as &$v){
  $b[] = &$v;
 }
  $b[2]='11'; //make changes in any element,  
     //will reflect both array
  var_dump($a);
  var_dump($b);

Here is a working demo: https://ideone.com/icgVJY

0
source

Source: https://habr.com/ru/post/1687058/


All Articles