Odd array_merge_recursive behavior with string keys - php

I'm trying to use array_merge_recursive to merge two data structures.
<?php
$testSite = array(
'name' => 'test site',
'modules' => array(
'foo' => 'true',
'bar' => 'true'
)
);
$testData = array(
'modules' => array(
'bar' => 'false'
)
);
$testSite = array_merge_recursive($testSite, $testData);
Note that I'm using strings instead of booleans for debug printing purposes
I would expect $testSite to be the exact same after this code has ran, except for the modules.bar property, which I'd expect to see being changed to false. What happens instead, as seen in this live example, is that bar is turned into an array containing it's old value and the value false is appended to that.
The documentation page reads that this is what will happen for numeric keys, but these are all strings keys. Can anyone shed some light on this?

I think you want array_replace_recursive.
array_merge_recursive() vs. array_replace_recursive()

Related

Multidimensional Array Not Echoing As Expected

I am setting this array manually:
$schools = array(
'Indiana University'=>array(
'initials'=>'IU',
'color'=>'red',
'directory'=>'indiana'
)
);
But it won't echo "IU" when I use:
echo $schools[0][0];
It does show correctly when I do:
print_r($schools);
I'm sure I'm messing up something dumb, but I have no idea what and I've been staring at it for hours. This array is actually part of a larger array with multiple universities, but when I trim it down to just this, it doesn't work.
PHP arrays support two types of keys - numerical and strings.
If you just push a value onto an array, it will use numerical keys by default. E.g.
$schools[] = 'Indiana University';
echo $schools[0]; // Indiana University
However, when you use string keys, you access the array values using the string key. E.g.
$schools = array(
'Indiana University' => array(
'initials' => 'IU',
'color' => 'red',
'directory' => 'indiana'
)
);
echo $schools['Indiana University']['initials']; // UI

Possible to use an associative array as $needle for in_array function?

In my company's code I stumbled about the following use-case of in_array(): (replica of what happens)
$theHystack = [
'id' => 3,
'location' => 'Berlin'
];
$theNeedle = [
'id' => 3,
'location' => 'Berlin'
];
echo in_array($theNeedle, $theHystack, true)
? 'true'
: 'false';
The documentation of in_array states that $needle can be of type mixed therefore it might be possible that this works.
To be certain I started to play around with the shown code however the result was always the same.
All results were false
The scenario was actually !in_array() thus it should return always true.
Question:
Is there a way of creating such a validation where you could validate an associative array with another associative array?
I'm looking for build-in php functions that could do something.

array_diff() strange behaviour

I have a routine in my code that computes the differences between two arrays in order create an SQL UPDATE statement.
As soon the routine starts I create a copy of the input array in order to manipulate it while the input one is kept untouched. When I'm ready to create the UPDATE statement I compute the difference between them, using the modified array as leading one.
In every test I ran both arrays were filled with key=value pairs and all values were strings, even when they're integers in the database (PDO behavior) and until now everything worked flawlessly.
But right now I've found something strange. Two different actions, in two different Controllers, but with the same logic are producing different differences:
This one works as expected:
$input = array(
'tid' => '3',
'enabled' => '1'
);
$modified = array(
'tid' => '3',
'enabled' => 0,
'modified' => '2014-11-26 15:17:55'
};
$diff = array(
'enabled' => 0,
'modified' => '2014-11-26 15:17:55'
);
$input is the result of a query. $modified is a copy of the first array manipulated through class methods. When I'm ready to create the statement, $diff is computed in order to send to PDO (or other driver) the correct statement.
Here, array_diff() works. the tid index is present in both array and it's ignored. The enabled, a simple on/off flag, is different and it's included. The datetime representation too.
But look the variables of this other case:
$input2 = array(
'sid' => '1',
'finished' => '0'
);
$modified2 = array(
'sid' => '1',
'finished' => 1,
'modified' => '2014-11-26 15:21:58'
);
$diff2 = array(
'modified' => '2014-11-26 15:21:58'
);
The same as before but with different field names. The sid is ignored but the finished is ignored too while it shouldn't because it is not present in the $input.
By replacing array_diff() with array_diff_assoc(), as expected, everything works, but why?
From the docs:
array array_diff ( array $array1 , array $array2 [, array $... ] )
Compares array1 against one or more other arrays and returns the
values in array1 that are not present in any of the other arrays.
In your example, $modified2 has an entry 'finished' which has value 1. But $input2 also has value 1 for key 'sid'. Thus, using array_diff($modified2, $input2) will result in the removal of every entry with value 1, no matter what the key is.
Using array_diff_assoc, it will only check to see if $input2 has the entry 'finished' => 1, which it does not, so the entry will not be removed.

What is the purpose of using depth in JSON encode?

I have this example code:
$array = array(
'GiamPy' => array(
'Age' => '18',
'Password' => array(
'password' => '1234',
'salt' => 'abcd',
'hash' => 'whirlpool'
),
'Something' => 'Else'
)
);
echo json_encode($array, JSON_PRETTY_PRINT);
I have seen in the PHP documentation that, since PHP 5.5.0 (thus recently), json_encode allows a new parameter which is the depth.
What is its purpose?
Why would I ever need it?
Why has it been added in PHP 5.5.0?
The option limits the depth that will be processed (d'uh). The depth of an array is measured by how deep it is nested. This is an array of depth 1:
array(
'foo',
'bar',
'baz'
)
This is an array of depth 2:
array(
array(
'foo'
),
array(
'bar'
),
array(
'baz'
)
)
// ------ depth ------>
If the input surpasses the maximum depth (by default 512), json_encode will simply return false.
Why you may use this is debatable, you may want to protect yourself from inadvertent infinite recursion or too much resource use. An array which is deeper than 512 levels probably has infinitely recursive references and cannot be serialised. But if you are sure your array is not infinitely recursive yet is deeper than 512, you may want to increase this limit explicitly. You may also want to lower the limit as a simple error catcher; say you expect the result to have a maximum depth but your input data may be somewhat unpredictable.

Computing difference by comparing nested arrays

I was under the impression that array_diff evaluates the difference between the values in the two arrays. But somehow it doesn't work...I am guessing nested arrays is the problem here. Clearly array_diff_assoc is not the solution as keys are irrelevant in this case.
I don't even want to make it go nested, just see whether the value (in this case, array) inside are identical or not.
$file_details = array(
array(
"uuid" => "45ebdbaa-380b-483b-80a2-73d7c53088e2",
"filename" => "train_failure.mp3",
),
array("uuid" => "97baa061-4208-4aeb-8136-eb76c0932a3d",
"filename" => "train_work1.mp3"
),
array("uuid" => "ksjdfls6-eb76c0932a3d",
"filename" => "train.mp3"
),
);
$items = array(
array(
"uuid" => "45ebdbaa-380b-483b-80a2-73d7c53088e2",
"filename" => "train_failure.mp3",
),
array(
"uuid" => "1233489eb76c0932a3d",
"filename" => "train.mp3"
),
);
print_r(array_diff($file_details,$items));
This returns an empty array...How should I go about fixing this?
My desired output is
array(
"uuid" => "97baa061-4208-4aeb-8136-eb76c0932a3d",
"filename" => "train_work1.mp3"
),
array(
"uuid" => "ksjdfls6-eb76c0932a3d",
"filename" => "train.mp3"
),
UPDATE -: *I know array_diff doesn't work for 1-d array, I'm just surprised there is no direct php function for doing a comparison on multidimensional arrays.*
Your array items are arrays and cannot be compared as strings (array_diff() will treat all values as strings - for example, it will try to stringify objects via calling their __toString() method).
You can use array_udiff() instead:
$rgResult=array_udiff($file_details, $items, function($rgX, $rgY)
{
return $rgX['uuid']<$rgY['uuid']?-1:$rgX['uuid']!=$rgY['uuid'];
});
array_diff() method is supposed to work with 1-d array.
From the array_diff() man page:
Note:
This function only checks one dimension of a n-dimensional array. Of
course you can check deeper dimensions by using
array_diff($array1[0], $array2[0]);

Categories