array issues when using ajax - php

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.

Related

How to change php array position with condition in Php

I am working with PHP,I have array and i want to change position of array, i want to display matching value in first position,For example i have following array
$cars=('Toyota','Volvo','BMW');
And i have variable $car="BMW" And i want to match this variable with array and if match then this array value should be at first in array
so expected result is (matching record at first position)
$cars=('BMW','Volvo','Toyota');
How can i do this ?
You can use array_search and array_replace for this purpose. try below mentioned code
$cars=array(0 =>'Toyota',1 =>'Volvo',2 =>'BMW');
$car="BMW";
$resultIndex = array_search($car, $cars); //get index
if($resultIndex)
{
$replacement = array(0 =>$car,array_search($car, $cars)=>$cars[0]); //swap with 0 index
$cars = array_replace($cars, $replacement); //replace
}
print_r($cars);
This can be solved in one line with array_merge and array_unique array functions.
$cars=['Toyota','Volvo','BMW'];
$car="BMW";
$cars2 = array_unique(array_merge([$car],$cars));
//$cars2: array(3) { [0]=> string(3) "BMW" [1]=> string(6) "Toyota" [2]=> string(5) "Volvo" }
$car is always at the beginning of the new array due to array_merge. If $car already exists in the $cars array, array_unique will remove it. If $car is not present in the $cars array, it is added at the beginning. If this behavior is not desired, you can use in_array to test whether $car is also contained in the $cars array.
The simplest is to "sort" by "Value = BMW", "Value != BMW".
The function that sorts and resets the keys (i.e. starts the resulting array from 0, which you want) is usort (https://www.php.net/manual/en/function.usort.php)
So your comparison function will be If ($a == "BMW") return 1, elseif ($b == "BMW") return -1, else return 0; (Paraphrased, don't expect that to work exactly - need to leave a bit for you to do!)

Value from php array seems incorrect

I am having an issue with understanding why my array containing 3 elements must be sliced into 2 parts each. I wish to access a number I'm pushing into the array only however it seems to print out the index rather than the 'key' value I pushed into it ($number).
I have a 2d array I'm pushing an ID and an integer into, and then sort it :
$array = [[]];
array_push($array, $doc[_id], $number);
array_multisort($array);
I then filter any empty elements:
$array = array_filter($array); //remove null elements
This all works as id expect however the array looks like this by this point:
unrated.array(5)
{
[2]=> object(MongoId)#32 (1)
{ ["$id"]=> string(24) "57b99696ce2350100b000029" }
[3]=> object(MongoId)#31 (1)
{ ["$id"]=> string(24) "57b998ccce2350181700002b" }
[4]=> object(MongoId)#33 (1)
{ ["$id"]=> string(24) "57b99a84ce2350100b00002b" }
[5]=> int(2) [6]=> int(3)
}
Again, this is fine however it means when I loop over the array using the code below it appears to be longer than 3 elements, as I have to slice from 0-6 instead of 0-3:
$array = array_slice($array, 0, 6, true); //only get 3 elements from array
foreach ($array as $key => $value) {
echo $key; //prints out values from 1-5 weirdly.... should just print the $number value
$id = $value->{'$id'};
}
What I am trying to achieve is to find the element in the array with the lowest possible value that was pushed earlier (array_push($array, $doc[_id], $number);) however because I cannot understand why the array is split into 6 rather than 3 parts its even more confusing.
Question in short : How do I access the $number pushed into the array and why is my array 6 seemingly 6 in size when it contains only 3 elements.
Any help would be appreciated, thanks.
To be clear, array_push simply pushes one or more values onto the end of an array. The first argument of array_push is the array you wish to push the value(s) to, and any subsequent argument is a list of values you wish to push. So what you're doing with array_push($array, $doc[_id], $number) is pushing two values ($doc[_id] and $number) to the end of the array $array. array_push will just use the next available index as the key when it adds those values to the array. It will not allow you to specify a key. This is the same thing as doing $array[] = $value.
To specify a key you must assign a value directly to the array key like so: $array[$key] = $value.

comparing two array php array_diff

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

Issue comparing two exploded php arrays to find overlap

I'm comparing the results of two exploded strings (results from a query), though when I use array_intersect to find the overlap of the arrays, I unfortunately only receive the overlap of those tags which are come first in each array...so for example if two arrays look like this:
Array1:
array(
[0]=> tag_a
[1]=> tag_b
)
Array2:
array(
[0]=> tag_a
[1]=> tag_b
)
Array_Intersect is only returning tag_a as a match. I expected the behavior of array_intersect to return tag_a as well as tab_b.
As you can see later in my code, I'm then using the matches (tags present in both arrays) to build the array contactarray. I'm able to build the array OK, it just doesn't contain the values I would have expected (ex: tag_b).
EDIT I've run several tests printing the contactarray and have applied various tag strings to those contacts and only the contacts who have have tag_a first (in the array) are being returned even though several other contacts have tag_a, though it's just not first in the array.
Thoughts?
if ($frequency == 'Weekly')
{
$data['query_tag'] = $this->db->get('tags');
foreach ($data['query_tag']->result() as $row2)
{
$contact_tags = $row2->tags;
$contact_tags_exploded = explode(",", $contact_tags);
$rule_tags_exploded = explode(",", $rule_tags);
$result = array_intersect($rule_tags_exploded, $contact_tags_exploded);
if(isset($result) && count($result) != 0){
$contactarray[] = $row2->contact_name;
}
}
}
Try array_uintersect()
Here $arr1 is your 1st array and $arr2 is second array
$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
print_r($intersect);
function compareDeepValue($val1, $val2)
{
return strcmp($val1['value'], $val2['value']);
}
This should give you both the values
Not Sure where is the problem you are facing copy paste this code and you will see the two values properly.
$arr = array( 'tag_a','tab_b ');
$arr = array('tag_a','tab_b ');
print_r(array_intersect($arr, $arr));
use master array for first argument and array to compare as second argument.
I am not sure what problem you have.

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.

Categories