This question already has an answer here:
Assign by reference bug
(1 answer)
Closed 6 years ago.
Consider the following PHP code segment.
$array1 = array(1,20);
$x = &$array1[1];
$array2 = $array1;
$array2[1] = 22;
print_r($array1[1]); // Output is 22
Here, $array2 is not referencing to $array1, but how to change value in $array2 by changing value of $array1?
If you want $array2 to be a reference of $array1 then you do the same thing as with $x.
$array2 = &$array1;
Now anything you change in either $array1 or $array2 is visible in both arrays since $array2 is just a reference to $array1.
Update
Thinking about it, what you may be looking at is a way to change a value, but still have a full copy of the arrays. This is doable with an object.
$obj = new stdClass();
$array1 = array(1, 20);
$array1[1] = $obj;
$array1[1]->color = 22;
$array2 = $array1;
$array2[1]->color = 33;
echo $array1[1]->color; // prints 33
This is because objects are always copied by reference, whereas numbers and strings are copied as is.
Related
This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 9 months ago.
Is it possible that I can get the data from the other array based on the value from another?
If I input value from array it will return a value from other array.
Example:
$arr1 = ['A','B','C'];
$arr2 = [1,2,3,];
Input: 2
Result: B
Do they need to be separate?
You could use array_combine() to assign a key to the value and then input is just $array[$input] - e.g.
$arr1 = ['A', 'B', 'C'];
$arr2 = [1, 2, 3];
$arr = array_combine($arr2, $arr1);
echo $arr[$_POST['input']]; # will display 2
Since your arrays have not been given any specific keys, they are assigned numerically indexes from PHP, starting from zero.
You can then use array_search() to get the key of the $arr2 array, and use that to find the value in $arr1.
$key = array_search($input, $arr2);
$output = $arr1[$key];
If either array has defined indexes, you can use array_values() to just get the values and get the numeric indexes from PHP again.
Live demo at https://3v4l.org/mf688
This function combine 2 or more arrays
<?php
$array1 = array('A', 'B', 'C');
$array2 = array('1', '2', '3');
$result = array_merge($array1, $array2);
print_r($result);
?>
Working with array $result above (1 of 2 possibility)
<?php echo $result[1]; ?>
Or use
<?php
$q = '2'; $key = array_search($q, $result);
if(!$key)
echo "This search returned no key and value pair";
else
echo "This search for value: " . $q . " is present in key: " . $key;
?>
This question already has answers here:
If null use other variable in one line in PHP
(13 answers)
Best way to give a variable a default value (simulate Perl ||, ||= )
(8 answers)
Closed 3 years ago.
Riht now I use array_merge_recursive but if one of my 3 arrays is null I get for echo json_encode($array4);
null
I have 3 arrays in my php file:
$array1 = json_decode($array1, TRUE);
$array2 = json_decode($array2, TRUE);
$array3 = json_decode($array3, TRUE);
If I echo each of the arrays:
echo json_encode($array1); = {"results":[{"cat_id":2,"cat_name":"bicycle repairs"}]}
echo json_encode($array2); = {"results":[{"cat_id":"4","cat_name":"plumber"},{"cat_id":"5","cat_name":"Electrician"},{"cat_id":"6","cat_name":"vet"}]}
echo json_encode($array3);= {"results":[{"cat_id":3,"cat_name":"Doctor"}]}
And then I merge these arrays together like this:
$array4 = array_merge_recursive($array1['results'], $array2['results'], $array3['results']);
Which would give me:
[{"cat_id":2,"cat_name":"bicycle repairs"},{"cat_id":"4","cat_name":"plumber"},{"cat_id":"5","cat_name":"Electrician"},{"cat_id":"6","cat_name":"vet"},{"cat_id":3,"cat_name":"Doctor"}]
But if any of $array1, $array2 or $array3 is null then $array4 doesn't work. How can I overcome this?
I'm afraid that the library only admits arrays as arguments (https://www.php.net/manual/en/function.array-merge-recursive.php).
So if you want merge all elements I advise you that use ?? (Null Coalescing operator) that return the first params if isset and is not null, you can do something like this:
array_merge_recursive($array1['results']??[], $array2['results']??[], $array3['results']??[])
I would make a helper function to check if you variable is an Array. If not just make it an empty one
function MakeArray($arr){
if (!is_array($arr)) return [];
return $arr;
}
$arr1 = MakeArray([1,2,4]);
$arr2 = MakeArray([5,6]);
$arr3 = MakeArray(NULL);
This way you can guarantee that it will work even if you pass, for example, a string
What I have
$array1 = [1,1,1];
$array2 = [1,1];
What I'm doing:
array_diff( $array1, $array2 );
What I expected:
array(1) { 1 }
What I got
array(0) { }
How do I subtract two arrays to get every discrepancy?
Edit:
My example was incomplete, sorry.
If we also have values like this:
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
I would expect
[1,1,2,1] - [1,1,1,2] = []
array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().
So this should work for you:
<?php
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
function caseCmpSort($a, $b){
return strcasecmp($a, $b);
}
usort($array1, "caseCmpSort");
usort($array2, "caseCmpSort");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
output:
Array ( )
use array_diff_assoc
$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)
try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb
So you should check array key differences too. Have you tried array_diff_assoc()?
http://php.net/manual/en/function.array-diff-assoc.php
From manual:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.
$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));
Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.
$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));
<?php
$n = array(1,1,1);
$m = array(1,1);
$r = array_diff_assoc($n,$m);
var_dump($r);
?>
I have two array inputs like this :
$array1 = [1,2,3,4,6];
$array2 = [1,3];
$output = array_merge(array_diff($array1,$array2),array_diff($array2,$array1));
Now I want to check array1 with array 2 and eliminate 1 and 3 in $array1
and the output I am expecting is
$output = [2,4,6];
but in this method I get some bugs, when array2 have single value e.g.: $array2 = [1]; , $array1 = [1,2,3,4,6]; the output should be $output = [2,3,4,6];. But I am getting $array1 all values [1,2,3,4,6];
Simple :)
(Just un-complicate your code and you don't need anything new for that)
<?php
$array1 = array(1,2,3,4,6);
$array2 = array(1,3);
$result = array_diff($array1, $array2);
print_r($result);
?>
Demo
In Your style it can even be a one liner :P
<?php print_r(array_diff(array(1,2,3,4,6), array(1,3))); ?>
This question already has answers here:
Create an assoc array with equal keys and values from a regular array
(3 answers)
Closed 6 years ago.
I have this array:
$a = array('b', 'c', 'd');
Is there a simple method to convert the array to the following?
$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');
$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one element.
Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}