I have two arrays (in PHP):
ArrayA
(
[0] => 9
[1] => 1
[2] => 2
[3] => 7
)
ArrayB
(
[0] => 1
[1] => 1
[3] => 8
)
I want to make two new arrays, where I have only the elements declared in both of the arrays, like the following:
ArrayA
(
[0] => 9
[1] => 1
[3] => 7
)
ArrayB
(
[0] => 1
[1] => 1
[3] => 8
)
In this example ArrayA[2] doesn't exist, so ArrayB[2] has been unset.
I wrote this for loop:
for ($i = 0, $i = 99999, $i++){
if (isset($ArrayA[$i]) AND isset($ArrayB[$i]) == FALSE)
{
unset($ArrayA[$i],$ArrayB[$i]);
}
}
But it's not great because it tries every index between 0 and a very big number (99999 in this case). How can I improve my code?
The function you're looking for is array_intersect_key:
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
Since you want both arrays, you'll have to run it twice, with the parameters in opposite orders, as it only keeps keys from the first array. An example:
$arrayA_filtered = array_intersect_key($arrayA, $arrayB);
$arrayB_filtered = array_intersect_key($arrayB, $arrayA);
Also, although a for loop wasn't ideal in this case, in other cases where you find yourself needing to loop through sparse array (one where not every number is set), you can use a foreach loop:
foreach($array as $key => $value) {
//Do stuff
}
One very important thing to note about PHP arrays is that they are associative. You can't simply use a for loop, as the indices are not necessarily a range of integers. Consider what would happen if you applied this algorithm twice! You'd get out of bounds errors as $arrayA[2] and $arrayB[2] no longer exist!
I would iterate through the arrays using nested foreach statements. I.e.
$outputA = array();
$outputB = array();
foreach ($arrayA as $keyA => $itemA) {
foreach ($arrayB as $keyB => $itemB) {
if ($keyA == $keyB) {
$outputA[$keyA] = $itemA;
$outputB[$keyB] = $itemB;
}
}
This should give you two arrays, $outputA and $outputB, which look just like $arrayA and $arrayB, except they only include key=>value pairs if the key was present in both original arrays.
foreach($arrayA as $k=>$a)
if (!isset($arrayB[$k]))
unset($arrayA[$k];
Take a look to php : array_diff
http://docs.php.net/manual/fr/function.array-diff.php
Related
Ran into a little snag and wondering if there is a "best practices" way around it.
So I just learned that "A php foreach will execute on the entire array regardless. Test unsetting a value that is next in iteration. It will iterate on the offset, but the value will be null. – Kevin Peno Dec 22 '09 at 21:31" from How do you remove an array element in a foreach loop?
It's the first part of that that is messing with me. I'm iterating through an array with foreach. It's a search function so I'm removing the element I just searched for, so when the loop runs again its minus that element.
I do NOT want to reindex if at all possible, although if I have to I can.
Array
(
[0] => Array
(
[0] => a
[1] => aa
[2] => aaa
)
[1] => Array
(
[0] => b
[1] => bb
[2] => bbb
)
[2] => Array
(
[0] => c
[1] => cc
[2] => ccc
)
[3] => Array
(
[0] => d
[1] => dd
[2] => ddd
)
)
foreach($array as $key=>$value) {
$searchresult[] = search function returns various other keys from array
foreach($searchresult as $deletionid) {
unset($array[$deletionid]);
}
}
So on the first iteration it uses $array[0] obviously but the $searchresults might return 4,5,6,7. So those keys are removed from $array.
Yet the foreach loop still iterates through those and gives me back a bunch of empty arrays.
I did read How does PHP 'foreach' actually work? and I get some of it.
Thanks
In my opinion, the best way to remove array elements based on indexes is to use the array_* set of functions, like array_diff and array_intersect (or array_diff_key and array_intersect_key in your situation).
$indexes_to_remove = array(2,3,4);
$indexes_to_remove = array_flip($indexes_to_remove);
$array = array_diff_key($array,$indexes_to_remove);
If the array is guaranteed to be exhausted at some point, you can use this:
while (true) {
$searchresult[] = search function returns various other keys from array
foreach($searchresult as $deletionid) {
unset($array[$deletionid]);
}
if (count($array) === 0) {
break;
}
}
And yes I know while (true) is pretty evil, but I find in cases like these it does exactly what is needed.
If you want to prevent it from infinite looping you could always add a variable, increment each iteration, and break when it reaches a high value that should never happen (like 10 * count($array))
Given
[0] => Array
(
[0] => ask.com
[1] => 2320476
)
[1] => Array
(
[0] => amazon.com
[1] => 1834593
)
[2] => Array
(
[0] => ask.com
[1] => 1127456
)
I need to remove duplicate values solely based on first value, regardless of what any other subsequent values may be. Notice [0][1] differs from [2][1] yet I consider this as a duplicate because there are two matching first values. The other data is irrelevant and shouldn't be considered in comparison.
Try this, assuming that $mainArray is the array you have.
$outputArray = array(); // The results will be loaded into this array.
$keysArray = array(); // The list of keys will be added here.
foreach ($mainArray as $innerArray) { // Iterate through your array.
if (!in_array($innerArray[0], $keysArray)) { // Check to see if this is a key that's already been used before.
$keysArray[] = $innerArray[0]; // If the key hasn't been used before, add it into the list of keys.
$outputArray[] = $innerArray; // Add the inner array into the output.
}
}
print_r($outputArray);
I am new to php and still learning the language,
let say I have two array
For Example
Array
(
[house_id] => 6
[name] => Lake Villa
[floor] => 5
[unit] => 25
)
Array
(
[house_id] => 6
[name] => Lake Villa
[floor] => 5
[unit] => 25
[parking_id] => 9
[resident_count] => 4
)
How do i get the keys of 1st array onto second, what i am saying is, i just need house_id, name, floor, unit from second array and discard rest of the information.
However, they key is not same and dynamic, which means the first array key whatever returned is also present on second but with additional information. The information above is just an example and the keys might varies but whatever key on first array contains on second array too.
I tried this, but isn't working:
foreach($arr1 as $k=>$v) {
foreach($arr2 as $j=>$w) {
if(isset($arr2[$k]))
$arr[$k] = $w;
}
}
You could use array_intersect_key, to merge the arrays.
$newArray = array_intersect_key($array2, $array1);
Use array_intersect_key().
array_intersect_key() returns an array containing all the entries of
array1 which have keys that are present in all the arguments.
Code
var_dump(array_intersect_key($array1, $array2));
foreach($arr2 as $key=>$val){
if(!array_key_exists($key,$arr1))
unset($arr2[$key]);
}
change condition from
if(isset($arr2[$k]))
to
if($arr1[$k] == $arr2[$j]) // it will work.
and isset is used for checking the variable is set or not.
Try this:
foreach($arr2 as $k=>$v) {
//Check if key is in first array
if(!isset($arr1[$k])) {
//Key not in first array, remove from second array.
unset($arr2[$k]);
}
}
try this
$result_array = array_intersect_key($arr2, $arr1);
So here's what I see this code doing:
An array is made
A loop iterates 10 times
A new array is created
A reference to this new array is saved in the first array
10 arrays now reside in the original array with values 0, 1, 2, 3...
What really happens:
WTF?
Code:
<?php
header('Content-type: text/plain');
$arrays = array();
foreach(range(0, 10) as $i)
{
$arr = array();
$arr[0] = $i;
$arrays[] = &$arr;
}
print_r($arrays);
Output:
Array
(
[0] => Array
(
[0] => 10
)
[1] => Array
(
[0] => 10
)
[2] => Array
(
[0] => 10
)
[3] => Array
(
[0] => 10
)
[4] => Array
(
[0] => 10
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 10
)
[7] => Array
(
[0] => 10
)
[8] => Array
(
[0] => 10
)
[9] => Array
(
[0] => 10
)
[10] => Array
(
[0] => 10
)
)
I would like to know exactly why apparently only the 10th array is referred to ten times, instead of every instance of the arrays being referred to one each.
Also if somebody who isn't just thinking WTF (like me) would like to edit the title, feel free to do so.
The line
$arr = array();
does not create a new array but rather assigns an empty array to the already existing reference.
If you want the variable name to "point" to a different array in memory, you have to unset() (or "disconnect") it first before assigning an empty array to it:
foreach(range(0, 10) as $i)
{
unset($arr);
$arr = array();
$arr[0] = $i;
$arrays[] = &$arr;
}
This is because the only operations that can make a variable point to something else is the reference assignment (=&) and the unset().
What happens here is that by inserting a reference to $arr inside $arrays, you are effectively adding the exact same array 10 times -- and each reference to the array has the value last assigned to it (i.e. the one produced when $i is 10).
It's not clear what you intend to achieve by inserting a reference in each iteration -- either removing the & or putting unset($arr) at the beginning of the loop would give you the expected behavior. What are you trying to accomplish?
Think about it this way. You do $arrays[] = &$arr; 10 times. This stores a reference to the local variable $arr 10 times. Since it's the same variable (the variable's scope is the entire function), it stores the same reference all 10 times. Thus, why should you expect the 10 elements to be different?
The reference you are storing has nothing to do with the value of $arr; it just has to do with the variable $arr. When you print the reference it prints the value of $arr at that time.
It's because you're storing a reference to the array that $arr points to in the array. And you keep overwriting that array with the latest number. All references in $arr will point to the same array in the end.
I don't know what you expect to get out of this in the end, but getting rid of & should fix this behavior.
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example