How does foreach traverse array? - php

From what I have found foreach traverses array in the order of adding elements. See this code:
$array = array();
$array[0] = "me0";
$array[1] = "me1";
$array[2] = "me2";
$array[4] = "me4";
$array[5] = "me5";
//changing
$array[3] = "me3Changed";
foreach($array as $item)
{
echo $item.'<br />';
}
echo '<br />';
ksort($array);
foreach($array as $item)
{
echo $item.'<br />';
}
which outputs:
me0
me1
me2
me4
me5
me3Changed
me0
me1
me2
me3Changed
me4
me5
This shows that the array is not traversed in a way for($i;$i<$arrayLength;$i++)
how is it traversed than? Assuming that php is written in C++ it should be using some c++ functions that do it this way. Can anyone explain to me how does foreach traverse arrays?
C++ example of traversing array by index:
std::string arr[10];
arr[0] = "me0";
arr[1] = "me1";
arr[2] = "me2";
arr[4] = "me4";
arr[5] = "me5";
//changing
arr[3] = "me3Changed";
for(int x = 0; x < 6;x++)
{
std::cout << arr[x] << std::endl;
}

PHP arrays are ordered key-value stores. Meaning the keys have an order, which is the order in which they were added to the array (or spliced together or sorted or whatever determined the order). foreach traverses arrays in this inherent, built-in order.
I don't know if this compares to anything in C. PHP's arrays are one of its more unique features. Most languages have key-value stores (dictionaries/hashes) or ordered arrays (lists). PHP has ordered key-value stores as its only array type.

The array is formed as you add in the key/value pair, look here. Hence, foreach traverses in that order as well.
Whereas, you are comparing it with a loop for($i;$i<$arrayLength;$i++) where you are specifying the index, hence, its ALWAYS going to search for that key, and then print its corresponding value.
Edit: Example explaining the above.

Related

PHP - Elegantly extract the numeric indices in array a that are not in array b (not array_diff_key)

Suppose you have two arrays $a=array('apple','banana','canaple'); and $b=array('apple');, how do you (elegantly) extract the numeric indices of elements in array a that aren't in array b? (in this case, indices: 1 and 2).
In this case, array a will always have more elements than b.
Note, this is not asking for array_diff_key, but rather the numeric indices in the array with more elements that don't exist in the array with fewer elements.
array_diff gets you half way there. Using array_keys on the diff gets you the rest of what you want.
$a = ['apple','banana','canaple'];
$b = ['apple'];
$diff = array_diff($a, $b);
$keys = array_keys($diff);
var_dump($keys); // [1, 2]
This is because array_diff returns both the element and it's key from the first array. If you wanted to write a PHP implementation of array_diff it might look something like this...
function array_diff(Array ... $arrays) {
$return = [];
$cmp = array_shift($arrays);
foreach ($cmp as $key => $value) {
foreach($arrays as $array) {
if (!in_array($value, $array)) {
$return[$key] = $value;
}
}
}
return $return;
}
This gives you an idea how you might achieve the result, but internally php implements this as a sort, because it's much faster than the aforementioned implementation.

PHP / json encode wrongly interprets as associative array

Edit1: The problem: I want to convert in php a associative array to a indexed one. So I can return it via json_encode as an array and not as an object. For this I try to fill the missing keys. Here the description:
Got a small problem, I need to transfer a json_encoded array as an array to js. At the moment it returns an Object. I´m working with Angular so I really need an Array. I try to explain it as much as possible.
$arrNew[0][5][0][0][1]["id"] = 1;
//$arrNew[0][0][0][0][1] = "";
//$arrNew[0][1][0][0][1] = "";
//$arrNew[0][2][0][0][1] = "";
//$arrNew[0][3][0][0][1] = "";
//$arrNew[0][4][0][0][1] = "";
$arrNew[0][5][0][0][1]["name"] = 'Test';
var_dump($arrNew);
So if I return it now It returns the second element as object cause of the missing index 0-4 and the 4th element cause of the missing index 0 (associative array -> object)
So if I uncomment the block it works like a charm. Now I have the problem its not every time the element 5 sometime 3, 4 or something else so I build a function which adds them automaticly:
$objSorted = cleanArray($arrNew);
function cleanArray($array){
end($array);
$max = key($array) + 1; //Get the final key as max!
for($i = 0; $i < $max; $i++) {
if(!isset($array[$i])) {
$array[$i] = '';
} else {
end($array[$i]);
$max2 = key($array[$i]) + 1;
for($i2 = 0; $i2 < $max2; $i2++) {
.... same code repeats here for every index
So if I vardump it it returns:
The problem:
On js side its still an object, what I also see is that the elements are not sorted. So I think somehow PHP sees it still as an associative array. Any clue why this happens ? The key is set with the index of the loop and has to be a integer value.
PS: I know reworking it in JS is possible but would have be done nearly on every request with a huge load of loops
If I understand your problem, you create a sparse multidimensional array of objects. Because the arrays have gaps in the keys, json_encode() produces objects on some levels but you need it to produce arrays for all but the most inner level.
The following function fills the missing keys (starting from 0 until the maximum value used as numeric key in an array) on all array levels. It then sorts each array by their keys to make sure json_encode() encodes it as array and not object.
The sorting is needed, otherwise json_encode() generates an object; this behaviour is explained in a note on the json_encode() documentation page:
When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.
// If $arr has numeric keys (not all keys are tested!) then returns
// an array whose keys are a continuous numeric sequence starting from 0.
// Operate recursively for array values of $arr
function fillKeys(array $arr)
{
// Fill the numeric keys of all values that are arrays
foreach ($arr as $key => $value) {
if (is_array($value)) {
$arr[$key] = fillKeys($value);
}
}
$max = max(array_keys($arr));
// Sloppy detection of numeric keys; it may fail you for mixed type keys!
if (is_int($max)) {
// Fill the missing keys; use NULL as value
$arr = $arr + array_fill(0, $max, NULL);
// Sort by keys to have a continuous sequence
ksort($arr);
}
return $arr;
}
// Some array to test
$arrNew[0][5][0][0][1]["id"] = 1;
$arrNew[0][3][0][2][1]["id"] = 2;
$arrNew[0][5][0][0][1]["name"] = 'Test';
echo("============= Before ==============\n");
echo(json_encode($arrNew)."\n");
$normal = fillKeys($arrNew);
echo("============= After ==============\n");
echo(json_encode($normal)."\n");
The output:
============= Before ==============
[{"5":[[{"1":{"id":1,"name":"Test"}}]],"3":[{"2":{"1":{"id":2}}}]}]
============= After ==============
[[null,null,null,[[null,null,[null,{"id":2}]]],null,[[[null,{"id":1,"name":"Test"}]]]]]
The line $arr = $arr + array_fill(0, $max, NULL); uses NULL as values for the missing keys. This is, I think, the best for the Javascript code that parses the array (you can use if (! arr[0]) to detect the dummy values).
You can use the empty string ('') instead of NULL to get a shorter JSON:
[["","","",[["","",["",{"id":2}]]],"",[[["",{"id":1,"name":"Test"}]]]]]
but it requires slightly longer code on the JS side to detect the dummy values (if (arr[0] != '')).

Which is the best and the most efficient way to find and store non existent values between two arrays in both sides?

Perhaps this has been asked several times but I can't find the right answer so here goes.
I have two arrays: one with ~135732 and the other one with ~135730 elements. I need to find which items are on the first but not on the second and viceverse and don't know is there is an easy way to achieve that.
This is what I would do it:
$countArr1 = count($arr1);
$countArr2 = count($arr2);
for($i=0; $i < $countArr1; $i++) {
// Check whether current element on $arr1 is on $arr2 or not
if (!in_array($arr1[$i], $arr2)) {
// if it doesn't then add it to $newArr
$newArr[] = $arr1[$i];
}
}
Then I would do the same but inverse for $arr2. In huge arrays could take a while and also could kill memory or server resources, even if it's executed from CLI so which is the best and the most efficient, regarding use of resources, way to achieve this?
EDIT
Let's clear this a bit. I get $arr1 from DB and $arr2 comes from other place. So the big idea is to find which items needs to be updated and which ones needs to be added also which ones needs to be marked as obsolete. In less and common words:
if element is on $arr1 but doesn't exists on $arr2 should be marked as obsolete
if element comes in $arr2 btu doesn't exists on $arr1 then needs to be added (created)
otherwise that element just need to be updated
Clear enough? Feel free to ask everything in order to help on this
EDIT 2
Based on #dakkaron answer I made this code:
// $arr1 and $arr2 are previously built
$sortArr1 = asort($arr1);
$sortArr2 = asort($arr2);
$countArr1 = count($sortArr1);
$countArr2 = count($sortArr2);
$i = $j = 0;
$updArr = $inactiveArr = $newArr = [];
echo "original arr1 count: ", count($arr1), "\n";
echo "original arr2 count: ", count($arr2), "\n";
echo "arr1 count: ", $countArr1, "\n";
echo "arr2 count: ", $countArr2, "\n";
while ( $i < $countArr1 && $j < $countArr2) {
if ($sortArr1[$i] == $sortArr2[$j]) {
//Handle equal values
$updArr[] = $sortArr1[$i];
$i++; $j++;
} else if ($sortArr1[$i] < $sortArr2[$j]) {
//Handle values that are in arr1 but not in arr2
$inactiveArr[] = $sortArr1[$i];
$i++;
} else {
//Handle values that are in arr2 but not in arr1
$newArr[] = $sortArr2[$j];
$j++;
}
}
echo "items update: ", count($updArr), "\n", "items inactive: ", count($inactiveArr), "\n", "items new: ", count($newArr), "\n";
And I got this output:
original arr1 count: 135732
original arr2 count: 135730
arr1 count: 1
arr2 count: 1
items update: 1
items inactive: 0
items new: 0
Why sort count returns 1?
You could take avantage of array_diff: http://php.net/manual/en/function.array-diff.php
Edit
A php function construct is more likely to perform better than an equivalent user-defined one. Searching I found this, but the size of your array is way smaller, and in the end I believe you should benchmark a prototype script with candidate solutions.
See my last comment.
The best solution I can think of would be to first sort both arrays and then compare them from the bottom up.
Start with the lowest element in both arrays and compare them.
If they are equal, take them and move up one element on both arrays.
If they are different, move up one element on the array with the lower value.
If you reached the end of one of the arrays you are done.
After the sorting this should take about O(n) complexity.
This is a bit of code in pseudocode:
arr1 = ...
arr2 = ...
arr1.sort();
arr2.sort();
i1 = 0;
i2 = 0;
while (i1<arr1.length() && i2<arr2.length()) {
if (arr1[i1]==arr2[i2]) {
//Handle equal values
i1++; i2++;
} else if (arr1[i1]<arr2[i2]) {
//Handle values that are in arr1 but not in arr2
i1++;
} else {
//Handle values that are in arr2 but not in arr1
i2++;
}
}
Other than that, if you don't want to implement it yourself, just use array_diff
The best solution i can think of is to sort the second array, and try to look for values from the first array using binary search,
this would take O(nLog(n)) complexity
Since your values are strings, you could take the advantage of PHP’s implementation of arrays using a hash-table internally with O(1) for key lookups:
$diff = [];
// A \ B
$lookup = array_flip($b); // O(n)
foreach ($a as $value) { // O(n)
if (!isset($lookup[$value])) $diff[] = $value;
}
// B \ A
$lookup = array_flip($a); // O(n)
foreach ($b as $value) { // O(n)
if (!isset($lookup[$value])) $diff[] = $value;
}
So in total, it’s O(n) in both space and time.
Of course, in the end you should benchmark it to see if it’s actually more efficient than other solutions here.
Fill hashtable-based dictionary/map (don't know how it is called in PHP) with the second array elements, and check whether every element of the first array presents in this dictionary.
Usual complexity O(N)
for A in arr2
map.insert(A)
for B in arr1
if not map.contains(B) then
element B is on $arr1 but doesn't exists on $arr2
note that this approach doesn't address all problems in your edited question

Find the number of objects in a json array

I have searched a lot and I found few methods to find the length of my JSON array. I have tried:
count
json.length
but these return 1, instead of the actual length. I want to show it using PHP.
My json is:
$huge = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
How can I find the number of objects in my JSON array?
You need to decode the json object and then count the elements in it ..
$json_array = json_decode($json_string, true);
$elementCount = count($json_array);
You'll need to decode into PHP arrays before you do any work with the data.
Try:
$hugeArray = json_decode($huge, true); // Where variable $huge holds your JSON string.
echo count($hugeArray);
If you need to count to a lower depth, you'll need to iterate through the array.
For example, if you want to count the number of elements in the next layer, you can do:
foreach ($hugeArray as $key => $value) {
echo $key.' - '.count($value);
}
However, this isn't necessarily meaningful because it depends on what you are trying to count, what your goal is. This block only counts the number of elements 1 layer underneath, regardless of what the actual numbers could mean.
First decode your json and after that use count on it.
$huge='[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
$arr = json_decode($huge,true);
echo count($arr);
Object (an unordered collection of key:value pairs with the ':' character separating the key and the value, comma-separated and enclosed in curly braces; ...)
Wikipedia: JSON
So, all you have to do are just count opened curly braces.
substr_count($huge , '{');
But... If you are storing some strings with '{' in json you can't do it. In that way you have to write your own simple parser or regular expression.
But... the easies way to json_decode. And use recursive function if you want to get count of all objects in json.
function count_objects($value)
{
if (is_scalar($value) || is_null($value))
$count = 0;
elseif (is_array($value))
{
$count = 0;
foreach ($value as $val)
$count += count_objects($val);
}
elseif (is_object($value))
{
$count = 1;
$reflection_object = new \ReflectionObject($value);
foreach ($reflection_object->getProperties() as $property)
{
$count +=count_objects($property->getValue($value));
}
}
return $count;
}
$huge = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
echo count_objects(json_decode($huge));
We can use ".sizeof()" function.
So

Interleaving multiple arrays into a single array

I need to merge several arrays into a single array. The best way to describe what I'm looking for is "interleaving" the arrays into a single array.
For example take item one from array #1 and append to the final array. Get item one from array #2 and append to the final array. Get item two from array #1 and append...etc.
The final array would look something like this:
array#1.element#1
array#2.element#1
.
.
.
The "kicker" is that the individual arrays can be of various lengths.
Is there a better data structure to use?
for example,
function array_zip_merge() {
$output = array();
// The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
for ($args = func_get_args(); count($args); $args = array_filter($args)) {
// &$arg allows array_shift() to change the original.
foreach ($args as &$arg) {
$output[] = array_shift($arg);
}
}
return $output;
}
// test
$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
If the arrays only have numeric keys, here's a simple solution:
$longest = max( count($arr1), count($arr2) );
$final = array();
for ( $i = 0; $i < $longest; $i++ )
{
if ( isset( $arr1[$i] ) )
$final[] = $arr1[$i];
if ( isset( $arr2[$i] ) )
$final[] = $arr2[$i];
}
If you have named keys you can use the array_keys function for each array and loop over the array of keys instead.
If you want more than two arrays (or variable number of arrays) then you might be able to use a nested loop (though I think you'd need to have $arr[0] and $arr[1] as the individual arrays).
I would just use array_merge(), but that obviously depends on what exactly you do.
This would append those arrays to each other, while elements would only be replaced when they have the same non-numerical key. And that might not be a problem for you, or it might be possible to be solved because of attribute order, since the contents of the first arrays' elements will be overwritten by the later ones.
If you have n arrays, you could use a SortedList, and use arrayIndex * n + arrayNumber as a sort index.

Categories