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 the content of $b is not reference of each element of $a?
What I expected of $b should be like {&a[0],&a[1],&a[2]} instead of {&a[2],&a[2],&a[2]}
Even i got error when i tried to reference 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 reference
Can someone explain to me why you can't pass a key as reference?
Because the language does not support this. You'd be hard-pressed to find this ability in most languages, hence the term 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?
The only way to provide better alternatives is to know your specific situation. If your keys map to table column names, then the best approach is to leave the keys as is and escape them at their time of use in your SQL.
Re:
Alternatives to Pass both Key and Value By Reference:
Reference works only for value
<?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);
Output will be
Array
(
[email] => orange#test
[topic] => welcome onboard
[timestamp] => 2017-10-6
)
Array
(
[0] => orange#test
[1] => welcome onboard
[2] => 2017-10-6
)
in foreach loop, you set every element of new array $b to reference variable $v. so at the end of foreach loop, they all point to last/current value of $v and that is "2017-10-6".
you can reference elaments of array $a this way:
foreach($a as $k => $var){
$b[] = &$a[$k];
}
Reference like this
foreach($a as &$v){
$b[] = &$v;
}
Live demo : https://eval.in/875570
If $a["email"] = "test"; changes it affects to $b automatically
Live demo : https://eval.in/875571
Here is the visa versa referencing. Each element of a reference to each element of b. And reverse referencing is also.
<?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 the working demo: https://ideone.com/icgVJY
Related
Learn php
<?php
$a = 3;
if ($a>1){
$arr = array (1,2,3);
}
foreach ($arr as $b) {
echo $b[0];
echo $b[1];
echo $b[2];
}
var_dump($arr);
?>
I don't know why it can not echo in foreach?
But var_dump($arr) still run with result:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
But when I wrote: $arr[] it can run.
<?php
$a = 3;
if ($a>1){
$arr[]= array (1,2,3);
}
foreach ($arr as $b) {
echo $b[0];
echo $b[1];
echo $b[2];
}
var_dump($arr);
?>
Result:
123
array(1) { [0]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } }
Both of them are same result with var_dump. So what different between $arr and $arr[] ?
These two lines:
$arr = array (1,2,3);
and
$arr[]= array (1,2,3);
are not equivalent. Look more closely at the two var_dump outputs, and you'll see the difference.
In the former, you're creating a one dimensional array - when you try to loop over it, you'll get an iteration with $b set to each of the three values (1, 2 and 3) in turn. Each time, $b is an integer. Any "index" of it will return null, since you can't deference scalar values (other than strings). This is defined in the manual here:
Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.
And when you echo null, nothing happens. It's the equivalent of an empty string, and so no output is produced.
In the second case, you're creating a two dimensional array. Writing
$arr[]= array (1,2,3);
when $arr is empty is the same as writing
$arr = array(array (1,2,3));
This time, when you loop over it, you get a single iteration, with $b set to the inner array. Now, echo-ing $b[0], $b[1] and $b[2] refers to the integers in the array, so you get your expected output of
123
Use this code instead of you written above:
<?php
$a = 3;
if ($a>1){
$arr = array (1,2,3);
}
foreach ($arr as $b) {
echo $b;
echo '<br>';
}
var_dump($arr);
?>
I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.
If I iterate through an array twice, once by reference and then by value, PHP will overwrite the last value in the array if I use the same variable name for each loop. This is best illustrated through an example:
$array = range(1,5);
foreach($array as &$element)
{
$element *= 2;
}
print_r($array);
foreach($array as $element) { }
print_r($array);
Output:
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 8 )
Note that I am not looking for a fix, I am looking to understand why this is happening. Also note that it does not happen if the variable names in each loop are not each called $element, so I'm guessing it has to do with $element still being in scope and a reference after the end of the first loop.
After the first loop $element is still a reference to the last element/value of $array.
You can see that when you use var_dump() instead of print_r()
array(5) {
[0]=>
int(2)
...
[4]=>
&int(2)
}
Note that & in &int(2).
With the second loop you assign values to $element. And since it's still a reference the value in the array is changed, too. Try it with
foreach($array as $element)
{
var_dump($array);
}
as the second loop and you'll see.
So it's more or less the same as
$array = range(1,5);
$element = &$array[4];
$element = $array[3];
// and $element = $array[4];
echo $array[4];
(only with loops and multiplication ...hey, I said "more or less" ;-))
Here's an explanation from the man himself:
$y = "some test";
foreach ($myarray as $y) {
print "$y\n";
}
Here $y is a symbol table entry referencing a string containing "some
test". On the first iteration you essentially do:
$y = $myarray[0]; // Not necessarily 0, just the 1st element
So now the storage associated with $y
is overwritten by the value from
$myarray. If $y is associated with
some other storage through a
reference, that storage will be
changed.
Now let's say you do this:
$myarray = array("Test");
$a = "A string";
$y = &$a;
foreach ($myarray as $y) {
print "$y\n";
}
Here $y is associated with the same
storage as $a through a reference so
when the first iteration does:
$y = $myarray[0];
The only place that "Test" string can
go is into the storage associated with
$y.
This is how you would fix this problem:
foreach($array as &$element)
{
$element *= 2;
}
unset($element); #gets rid of the reference and cleans the var for re-use.
foreach($array as $element) { }
I'd like to be able to extract some array elements, assign each of them to a variable and then unset these elements in the array.
Let's say I have
$myarray = array ( "one" => "eins", "two" => "zwei" , "three" => "drei") ;
I want a function suck("one",$myarray)as a result the same as if I did manually:
$one = "eins" ;
unset($myarray["one"]) ;
(I want to be able to use this function in a loop over another array that contains the names of the elements to be removed, $removethese = array("one","three") )
function suck($x, $arr) {
$x = $arr[$x] ;
unset($arr[$x]) ;
}
but this doesn't work. I think I have two prolbems -- how to say "$x" as the variable to be assigned to, and of function scope. In any case, if I do
suck("two",$myarray) ;
$two is not created and $myarray is unchanged.
Try this:
$myarray = array("one" => "eins", "two" => "zwei" , "three" => "drei");
suck('two', $myarray);
print_r($myarray);
echo $two;
function suck($x, &$arr) {
global $$x;
$$x = $arr[$x];
unset($arr[$x]);
}
Output:
Array
(
[one] => eins
[three] => drei
)
zwei
I'd build an new array with only the key => value pairs you want, and then toss it at extract().
You can do
function suck($x, $arr) {
$$x = $arr[$x] ;
unset($arr[$x]) ;
}
, using variable variables. This will only set the new variable inside the scope of "suck()".
You can also have a look at extract()
Why not this:
foreach ($myarray as $var => $val) {
$$var = $val;
unset($myarray[$var]);
echo "$var => ".$$var . "\n";
}
Output
one => eins
two => zwei
three => drei
If I've understood the question, you have two problems
The first is that you're setting the value of $x to be the value in the key-value pair. Then you're unsetting a key that doesn't exist. Finally, you're not returning anything. Here's what I mean:
Given the single element array $arr= array("one" => "eins") and your function suck() this is what happens:
First you call suck("one", $arr). The value of $x is then changed to "eins" in the line $x=$arr[$x]. Then you try to unset $x (which is invalid because you don't have an array entry with the key "eins"
You should do this:
function suck($x, $arr)
{
$tmp = $arr[$x];
unset($arr[$x]);
return $tmp
}
Then you can call this function to get the values (and remove the pair from the array) however you want. Example:
<?php
/* gets odd numbers in german from
$translateArray = array("one"=>"eins", "two"=>"zwei", "three"=>"drei");
$oddArray = array();
$oddArray[] = suck($translateArray,"one");
$oddArray[] = suck($translateArray, "three");
?>
The result of this is the array called translate array being an array with elements("eins","drei");
HTH
JB
pretty straightforward question actually..
is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?
I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?
function Combine($array1, $array2) {
if(count($array1) == count($array2)) {
$assArray = array();
for($i=0;$i<count($array1);$i++) {
$assArray[$array1[$i]] = $array2[$i];
}
return $assArray;
}
}
array_combine($keys, $values)
PS: Click on my answer! Its also a link!
you need array_combine.
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
There’s already an array_combine function:
$combined = array_combine($keys, $values);
hello everybody i will show you how to merge 2 arrays in one array
we have 2 arrays and i will make one array from them
$data_key = array('key1','key2');
$data_value = array('val1','val2');
lets declare the main array
$main_array = array();
now let's fill it with the 2 arrays
foreach ($data_key as $i => $key) {
$main_array[$key] = $data_value[$i];
}
now let's see the result by using var_dump($main_array);
array(2) {
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2"
}
i hope that can help someone :)