I have two arrays :
$arr = ["ham", "beef", "testing1"];
$arr1 = ["baby", "chicken", "wax"];
When merging them I get the following result :
var_dump(array_merge($arr, $arr1));
// ["ham", "beef", "testing1", "baby", "chicken", "wax"]
As you can see, the order is kept and they're added at the end of the first array. Can I be SURE that this is ALWAYS the case? Or the order is not necessarily kept? I found nothing in the docs about the order of the results.
You can read more in documentation:
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
So as you can see the values of second array are appended to the end of the previous one.
For duplicate keys the last one will override the previous one as it states in documentation:
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.
Related
I need to find the most common (most occurring) array in a multidimensional array. Not the most common values like this post - Find Common most values in multidimensional array in PHP - but rather the most common combination.
For example, if I have the following:
$a1=array(
array('704322062'),
array('678073776', '704322062'),
array('678073776', '704322062'),
array('704322064'),
array('704322062'),
array('678073776'),
array('678073776', '704322062')
);
I want to be able to detect that the array that occurs most often is array('678073776', '704322062') not that the string '704322062' is most common.
I've tried using array_intersect but couldn't get it working for this scenario.
Thanks!
array_count_values only works with scalar values, not when the items are arrays themselves. But we can still use that function, if we transform your arrays into strings first - by encoding them as JSON.
// fill temp array with items encoded as JSON
$temp = [];
foreach($a1 as $item) {
$temp[] = json_encode($item);
}
// count how many times each of those values occurs
$value_counts = array_count_values($temp);
// sort by number of occurrence, while preserving the keys
ksort($value_counts);
// pick the first key from the temp array
$first = array_key_first($value_counts);
This will get you ["678073776","704322062"] in $first now - you can json_decode it again, if you want your “original” array.
Note that this does not take into account, that two arrays could occur the same amount of times - then it will just pick the “random” first one of those. If you need to handle that case as well somehow, then you can determine the maximum value in $temp first, and then filter it by that value, so that only those keys of the corresponding arrays will be left.
I have two arrays with the same keys but different values. I need to merge it but if the values are the same leave only one of this
$array1 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1);
$array2 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_2);
I need to get:
$array_result = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1, 'address'=>$addres_2);
can anybody help to solve this?
array_merge does not work for me..
First you need to merge 2 arrays, using array_merge() function. then get the unique elements from the array using array_unique() function will get you the result
var_dump(array_unique(array_merge($array1, $array2)));
Edit
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.
php doc
Thanks #Marco
This is probably a very trivial question, but please bear with me.
I am trying to read a lot of data into an array of associative arrays. The data contains a lot of empty arrays and arrays with keys set and but all null values. I want to ignore those and only push arrays with at least one key mapped to a non-null value. (The data comes from an excel sheet and it has lots of empty cells that are registered as "set" anyway.) So far I have tried:
if(!empty(${$small_dummy}))
array_push(${$big_dummy}, ${$small_dummy});
That gets rid of the empty arrays but not the ones where all keys map to null. Is there a better way to do this than looping through the entire array and popping all null values?
Judging by the code you have already, you can change:
if(!empty(${$small_dummy}))
to:
if(!empty(array_filter(${$small_dummy})))
That will filter out all empty values (values evaluating to FALSE to be precise) and check if the resulting array is empty. Also see the manual on array_filter().
Note that this would also filter 0 values so you might need to write a custom callback function for array_filter().
You can try if(!array_filter($array)) { also
This isn't an ideal approach, but array_sum will return 0 if all values can't be cast to a numeric value. So :
$small_dummy = array("a" => null, "foo", "", 0);
if(array_sum($small_dummy) === 0)
would pass. But this is only the way to go if you are expecting the values to be numeric.
Actually, if the problem is that the array keys have values and therefor are not passing as empty(), the go with array_values:
if(!empty(array_values(${$small_dummy})))
I have an array with 18 values in it from which I select random values using $array[rand(0,17)]. I put these randomly selected values next to each other on the page. Within the array are 6 sets of values that I do not want to be put next to each other on the page. Is there any way that I can detect when the pairs are together and select new values because of that
warning: Do you know for sure that you won't get any degenerate cases where there are no possible orderings of the array? For example, if you won't allow the pairs [1,2] or [2,1] and the array you get is [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2], the you're out of luck. There's no way to display the array in the way you want, and a method like I describe below will never terminate.
I would use shuffle($array) and then iterate through the shuffled array one item at a time, to find out whether any value is "incompatible" with the item before it. If so, just reshuffle the array and try again. You can't predict how many tries it will take to get a shuffled array that works, but the amount of time it takes should be negligible.
To detect whether two values are compatible, I'd suggest making an array that contains all incompatible pairs. For example, if you don't want to have the consecutive pairs 1 and 3 or 2 and 5, then your array would be:
$incompatible = array(
array(1,3),
array(2,5) );
Then you'd iterate over your shuffled array with something like:
for ($i=1; i<count($array)-1; i++;) {
$pair = $array[i, i+1]; // this is why the for loop only goes to the next-to-last item
if in_array($pair, $incompatible) {
// you had an incompatible pair in your shuffled array.
// break out of the for loop, re-sort your array, and try again.
}
}
// if you get here, there were no incompatible pairs
// so go ahead and print the shuffled array!
Or use with unset() for remove the keys, or use by Session, for next skip.
Which one would you use?
Basically I only want to get the 1st element from a array, that's it.
Well, they do different things.
array_shift($arr) takes the first element out of the array, and gives it to you.
$arr[0] just gives it to you... if the array has numeric keys.
An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.
array_shift will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!
See here: http://php.net/manual/en/function.array-shift.php
You would use $arr[ 0 ]; array_shift removes the first element from the array.
EDIT
This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon's I think that it should actually stay up so that others can see that discourse.
The right answer:
reset is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0 index.
array_shift will remove and return the value which is found at reset
The OP made the assumption that $arr[0] is the first index is not accurate in that particular context.
$arr[0] only works if the array as numerical keys.
array_shift removes the element from the array and it modifies the array itself.
If you are not sure what the first key is , and you do not want to remove it from the array, you could use:
<?php
foreach($arr $k=>$v){
$value = $v;
break;
}
or even better:
<?php
reset($arr);
$value = current($arr);
If you have an associative Array you can also use reset($arr): It returns the first Element (doesn't remove), and sets the array pointer to this element.
But the fastest way is $arr[0].
Do you want to modify the arr array also? array_shift removes the first element of the array and returns it, thus the array has changed. $arr[0] merely gives you the first element.
I would use $arr[0] unless I explicitly wanted to modify the array. You may add code later to use the arr array and forget that it was modified.
given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.
arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.
arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.
A more convoluted but reliable method is:
$keys = array_keys($arr);
$first = $arr[$keys[0]];
with array_shif you have two operations:
retrive the firs element
shift the array
if you access by index, actually you have only one operation.
If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.
Edit: Use index 0 only if you know that the array has default keys starting from 0.
If you don't want to change the array in question, use $arr[0] (which merely gets the first element), otherwise if you want to remove the first element of $arr from $arr, use array_shift($arr).
For example:
$arr=array(3,-6,2);
$foo=$arr[0]; //$foo==3 and $arr==array(3,-6,2).
$bar=array_shift($arr); //$bar==3 and $arr==array(-6,2).
ETA: As others have pointed out, be sure that your array isn't an associative array (ie the keys are 0,1,...,(sizeof($arr)-1)), otherwise this probably won't work.