comparing two array php array_diff - php

I got an empty array when I compare two arrays that have the different key but the same value. Example: id has the same value like yy
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
What I want is :
$a = array('id'=>12,'id'=>2);

You can use array_merge_recursive() - (PHP 4 >= 4.0.1, PHP 5, PHP 7)
From PHP Manual:
array_merge_recursive — Merge two or more arrays recursively
<?php
$a = array('id'=>2,'name'=>'D','yy'=>12);
$b = array('id'=>12,'name'=>'D','yy'=>12);
$result = array_merge_recursive($a, $b);
$newArr = $result['id']; // get ID index. you can also get other indexes.
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[0] => 2
[1] => 12
)
Note that: you can not use same index name (ID) for this array array('id'=>12,'id'=>2);

As #Ghost mentioned, an associative array should not have the same keys.
I suggest to achieve the "expected result" in "nested arrays" manner using array_diff_assoc function(computes the difference of arrays with additional index check):
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
echo "<pre>";
$result_nested_arr = [array_diff_assoc($o, $n), array_diff_assoc($n, $o)];
var_dump($result_nested_arr);
// the output:
array(2) {
[0]=>
array(1) {
["id"]=>
int(2)
}
[1]=>
array(1) {
["id"]=>
int(12)
}
}
http://php.net/manual/en/function.array-diff-assoc.php

Related

Why "foreach" don't echo?

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);
?>

array issues when using ajax

I am trying to use ajax to compare two arrays to see if a particular value set is the same or not, so I filled both arrays with the same values and when i tested them my test says that they are not the same. The first array was made on fileA.php (with a while loop pulling directly from a database)and uses ajax to send it as a url variable to fileB.php (the responding file). On fileB.php I then use a $_GET to get the array , and create another array with a while loop pulling the exact same values directly from the database and compare the two . At this point the two arrays should be the same, but as I said earlier my test says they aren't .So I did a var_dump of both arrays and they looked different for some reason.
first array dump:
array(2) {
[0]=>
array(0) {
}
[1]=>
string(6) ",2,2,1"
}
second array dump:
array(3) {
[0]=>
array(0) {
}
[1]=>
string(1) "2"
[2]=>
string(1) "2"
[3]=>
string(1) "1"
}
array 1 is made on fileA.php
while ($row = mysql_fetch_assoc($res))
{
$iState[] = $row["state"];
}///end while
then i use ajax to send to fileB.php
js_array=<? echo json_encode($iState); ?>;
var url_js_array=js_array.join(',');
xmlhttp.open("GET","fileB.php?istate="+ url_js_array,true);
xmlhttp.send();
then in fileB.php(ajax response file) i retrieve the array
$iStateValues[] =$_GET["istate"] ;
then I create array 2 on fileB.php
while ($row = mysql_fetch_array($res))
{
$currentiState[]= $row["state"];
}///end while
then I compred the two
echo"\n\nsame test\n";
if($iStateValues==$currentiState)
echo "same";
else
echo "not same";
The var_dumps of the two arrays are different but they were created the exact same way . Wh is this?????
Your arrays are not the same, actually. Your first array (lets, say $arr1) has 2 elements, while your second array (lets, say $arr2) has 4 elements in it.
Definitely, the first element of both the arrays (i.e., $arr1[0] and $arr2[0]) is an empty array and that part of the arrays are similar.
Now, the remaining part of the first array (i.e. $arr1[1]) is a string: ",2,2,1", while the remaining part of the second array are more array values: 2, 2, 1 and is not a string.
i.e.:
$arr1[1] #=> string: ,2,2,1
$arr2[1] #=> string: 2
$arr2[2] #=> string: 2
$arr2[3] #=> string: 1
And, therefore, you can clearly see the two arrays are not equal.
You can compare two arrays for equality (preserving the order) using the === operator, like this:
$arr1 === $arr2 #=> false
If you only want to check whether the two arrays have the same values (irrespective of their order), you should use the == operator.
Your arrays are not equal because you modify them in your code!
PHP:
// This is not an array, but a json string
js_array=<? echo json_encode($iState); ?>;
JS:
// Just pass the whole json string and don't use join!
xmlhttp.open("GET","fileB.php?istate="+ url_js_array,true);
xmlhttp.send();
PHP:
// Create an array again with json_decode
$iStateValues[] = json_decode($_GET["istate"]);
To your second question, this is how you could compare arrays in PHP:
$array1 = array(1, 2, 3); // This is the same like $array1 = array(0 => 1, 1 => 2, 2 => 3);
$array2 = array(1, 2, 4);
$array3 = array(3, 2, 1);
var_dump($array1 == $array2); // false
var_dump($array1 == $array3); // false
var_dump($array2 == $array3); // true
var_dump($array1 === $array2); // false
var_dump($array1 === $array3); // false
var_dump($array2 === $array3); // false
"==" checks for the same elements and "===" for the correct order. So in your case, '===' would deliver the correct answer.

Printing more than one array using print_r or any other function in php

I need to print contents of multiple arrays in my code. Eg
function performOp($n, $inputArr, $workArr)
{
printf("Entered function, value of n is %d", $n);
print_r($inputArr);
print_r($workArr);
$width =0;
}
Now, Instead of writing print_r twice, is there any way I can write a single statement and print both the arrays ?
Also, If I want to print "Input array value is " before displaying the Array{}, is there a way to do so using printf or any other function?
I tried writing printf("Value of inputArray is %s ", print_r($inputArr), but this would not work.
Any help is really appreciated.
Thanks
Dumping the Variables
You can pass multiple arrays into var_dump().
var_dump( $array, $array2, $array3 );
For instance, the following:
$array = array("Foo", "bar");
$array2 = array("Fizz", "Buzz");
var_dump( $array, $array2 );
Outputs this:
array(2) { [0]=> string(3) "Foo" [1]=> string(3) "bar" }
array(2) { [0]=> string(4) "Fizz" [1]=> string(4) "Buzz" }
Note how it keeps both arrays distinct in the output as well.
Function with n-arguments
You could also use a function, calling upon func_get_args() for the arrays passed in:
function logArrays() {
$arrays = func_get_args();
for ( $i = 0; $i < func_num_args(); $i++ )
printf( "Array #%d is %s", $i, print_r($arrays[$i], true) );
}
logArrays( $array, $array2 );
Which, in this case, would output the following:
Array #0 is Array ( [0] => Foo [1] => bar )
Array #1 is Array ( [0] => Fizz [1] => Buzz )
Using json_encode() instead of print_r would output a slightly more readable format:
Array #0 is ["Foo","bar"]
Array #1 is ["Fizz","Buzz"]
User array_merge() to combine the arrays and then you can print them together.
If you prefer to use less function and have the advantage and simplicity of print_r() you combine these input value into new array inside the print_r(),
e.g I use this function to print raw unformatted output if my code (for debug) and this is the easiest method I reach.
function pre( $txt ) {
print_r( [ '<xmp> ' , $txt ,' </xmp> ' ] );
}

php array comparison index by index

If there are two array variable which contains exact same digits(no duplicate) but shuffled in position.
Input arrays
arr1={1,4,6,7,8};
arr2={1,7,7,6,8};
Result array
arr2={true,false,false,false,true};
Is there a function in php to get result as above or should it be done using loop(which I can do) only.
This is a nice application for array_map() and an anonymous callback (OK, I must admit that I like those closures ;-)
$a1 = array(1,4,6,7,8);
$a2 = array(1,7,7,6,8);
$r = array_map(function($a1, $a2) {
return $a1 === $a2;
}, $a1, $a2);
var_dump($r);
/*
array(5) {
[0]=>
bool(true)
[1]=>
bool(false)
[2]=>
bool(false)
[3]=>
bool(false)
[4]=>
bool(true)
}
*/
And yes, you have to loop over the array some way or the other.
You could use array_map:
<?php
$arr1= array (1,4,6,7,8) ;
$arr2= array (1,7,7,6,8) ;
function cmp ($a, $b) {
return $a == $b ;
}
print_r (array_map ("cmp", $arr1, $arr2)) ;
?>
The output is:
Array
(
[0] => 1
[1] =>
[2] =>
[3] =>
[4] => 1
)
Any way this job is done must be using looping the elements. There is no way to avoid looping.
No metter how you try to attack the problem and even if there is a php function that do such thing, it uses a loop.
You could use this http://php.net/manual/en/function.array-diff.php, but it will not return an array of booleans. It will return what data in array 1 is not in array 2. If this doesn't work for you, you will have to loop through them.
there's array_diff() which will return an empty array in case they are both equal.
For your spesific request, you'll have to iterate through the arrays and compare each item.

Manipulating multidimensional array in PHP?

array(2) {
[0]=>
object(stdClass)#144 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(5) "name1"
}
[1]=>
object(stdClass)#145 (2) {
["id"]=>
string(1) "4"
["name"]=>
string(5) "name2"
}
}
I want to add key and value (for example [distance] = 100;) to the objects in the array. After this I want to sort on the distance values. How can I achieve this?
To get structure such as yours you can do:
$arr = array();
$arr[0]->id = "2";
$arr[0]->name = "name1";
$arr[1]->id = "4";
$arr[1]->name = "name2";
To add "distance" you can do:
$arr[0]->distance = 100;
$arr[1]->distance = 200;
To sort you can use decorate/sort/undecorate pattern:
$arr = array_map(create_function('$o', 'return array($o->distance, $o);'), $arr); // transform array of objects into array of arrays consisted of sort key and object
sort($arr); // sort array of arrays
$arr = array_map('end', $arr); // take only last element from each array
Or you can use usort() with custom comparison function like this:
function compareDistanceFields($a, $b) {
return $a->distance - $b->distance;
}
usort($arr, "compareDistanceFields");
$my_array[0]->distance = 100;
$my_array[0]->distance = 101;
usort($my_array, "cmp");
function cmp($a, $b)
{
if ($a->distance == $b->distance)
return 0;
return ($a->distance > $b->distance) ? 1: -1;
}
What you have here is an array of hashes; that is, each element of your array is a hash (a structure containing elements, each of which is identified by a key).
In order to add a key and value, you just assign it, like this:
$array[0]["distance"]=100;
$array[1]["distance"]=300;
#and so on
PHP hashes and arrays in general are documented here.
Now, in order to sort your array (each of whose elements is a hash), you need to use the "uasort" function, which allows you to define a comparison function; in this comparison function you define the behavior you want, which is sorting on the value of the distance key.
Something like this:
// Comparison function, this compares the value of the "distance" key
// for each of the two elements being compared.
function cmp($a, $b) {
if ($a["distance"] == $b["distance"]) {
return 0;
}
return ($a["distance"] < $b["distance"]) ? -1 : 1;
}
Once this is defined, you call uasort like this:
uasort($array, 'cmp');
Find more documentation on uasort here.

Categories