Create an array of key difference using two array - php

How can we find key deference array using two arrays like
First Array :
$array_1 = array('300','200','500');
Second Array :
$array_2 = array('500','300','200');
$array_2 is generating by applying rsort to $array_1
Then i want to generate an array of key by comparing value of $array_1 and key of $array_2.Output will be an array of
$key_array = ('1','2','0');

Use array_flip() on $array_2 to convert the keys to values and vice versa. Then you can easily find the original keys.
$flip_2 = array_flip($array_2);
$key_array = array_map(function($el) use ($flip_2) { return $flip_2[$el]; }, $array_1);
DEMO

Try:
$array_1 = array('300','200','500');
$array_2 = array('500','300','200');
$key_array = array();
foreach($array_1 as $arr1) {
$key_array[] = array_search($arr1, $array_2); // get key in array_2 for value of array1
}
print_r($key_array);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 0
)

Related

How to delete array of element in array

I have two array. I want to remove if 2nd array exists in 1st array. For example
array1 = array ("apple","banana","papaya","watermelon","avocado");
array2 = array ("apple","avocado");
I want the output should be
Array ( [1] => banana [2] => papaya [3] => watermelon)
Here are some code that I'd tried.
foreach($array2 as $key){
$keyToDelete = array_search($key, $array1);
unset($array1[$keyToDelete]);
}
print_r($array1);
but the output is
Array ( [1] => banana [2] => papaya [3] => watermelon [4] =>avocado )
It only remove first element.
i also tried to do something like this
$result = array_diff($array1,$array2);
print_r($result);
but the output is it print all element in array1
Noted: I want the result need to be outside foreach loop
array_diff should be work.
<?php
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$array_diff = array_diff($array1, $array2);
print_r($array_diff);
?>
DEMO
output will be.
Array ( [1] => banana [2] => papaya [3] => watermelon)
You can also try below solution. result will be same.. using in_array Check if first array value not in the second tester that value in the new array 'final_result' for results.
in_array support (PHP 4, PHP 5, PHP 7)
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$final_result = array();
foreach($array1 as $value){
if(!in_array($value, $array2)){
$final_result[] = $value;
}
}
print_r($final_result);
?>
DEMO
With the help of array_filter() we can do it easily. It filters elements of an array using a callback function.
array_filter() iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
Here we have used use($array2) clause to access the external variable inside callback function. $array2 is needed to filter out $array1.
$array1 = array("apple","banana","papaya","watermelon","avocado");
$array2 = array("apple","avocado");
$array1 = array_filter($array1, function($item) use($array2) { return !in_array($item, $array2); });
print '<pre>';
print_r($array1);
Demo
The fastest way to do this is to create a set(associative array) of elements in $array2 and iterate over $array1 and check if element in $array1 exists in our set or not using isset(). We take advantage of the method/algorithm technique called hashing.
<?php
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$set = [];
foreach($array2 as $element){
$set[$element] = true;
}
$result = [];
foreach($array1 as $element){
if(!isset($set[$element])){
$result[] = $element;
}
}
print_r($result);
Demo: https://3v4l.org/PcS45

How to push a found array item into another array?

I have an array. But trying to separate items. For example:
$array1 = ["banana","car","carrot"];
trying to push car into another array which is $array2
$push = array_push($array1, "car") = $array2;
I try to find array_push usage for this but the documentation is all about. sending new item to array. Not array to array. Is this possible with array_push or need to use something else?
I need to search for the value car in $array1, push it into $array2 and remove it from $array1.
Here is a flexible solution that allows you to search by "car", then IF it exists, it will be pushed into the second array and omitted from the first.
Code: (Demo)
$array1 = ["banana","car","carrot"];
$needle = "car";
if (($index = array_search($needle, $array1)) !== false) {
$array2[] = $array1[$index];
unset($array1[$index]);
}
var_export($array1);
echo "\n---\n";
var_export($array2);
Output:
array (
0 => 'banana',
2 => 'carrot',
)
---
array (
0 => 'car',
)
You can push $array1 item car into $array2 as like below
$array2 = array();
$array1 = ["banana","car","carrot"];
array_push($array2, $array1[1]);
print_r($array2); /* OutPut Array ( [0] => car ) */
As you know $array1[1] has value is car so it will push it into $array2 by suing php built-in function array_push()
Hope this will help you.
$array1 = ["banana","car","carrot"];
$array2 = array_slice($array1, 1, 1);
unset($array1[1]);

How can i split array into two array based on integer value

Here is an example array I want to split:
(1428,217,1428)
How do I split it in 2 array like this?
(1428,1428)
(217)
I have tried following way but it's only return 1428 array.
$counts = array_count_values($array);
$filtered = array_filter($array, function ($value) use ($counts) {
return $counts[$value] > 1;
});
One way to solve this for your example data is to sort the array and use array_shift to get the first element of the array and store that in an array.
$a = [1428,217,1428];
sort($a);
$b = [array_shift($a)];
print_r($a);
print_r($b);
Result
Array
(
[0] => 1428
[1] => 1428
)
Array
(
[0] => 217
)
You can try this.
$array = array(1428,217,1428);
$array1 = array_slice($array, 0, 2);
$array2 = array_slice($array, 2, 3);
print_r($array1);
print_r($array2);
And the output will like this:-
Array
(
[0] => 1428
[1] => 217
)
Array
(
[0] => 1428
)
In your case it will only return 1428 since array_count_values returns an array with values as keys and their frequency as array value therefore $counts will be equal to array('1428' => 2, '217' => 1);
If I understood your question well you should do something like this:
$array1 = [1428, 217, 1428];
$result = [];
foreach($array1 as $value){
$result[$value][] = $value;
}
This will not create an array for each different value but will create a new element for each unique value in $result. The final value of $result will be array('1428' => [1428, 1428], '217' => [217]) . Which can be easily manipulated as if they were 2 different arrays.
Let me know if this works for you, if not I will try to update my answer according to your specification.

Multidimenssion array compare two arrays and update first array value

I want to filter a array by a number and update its status in the first array.
I have two array $arr1,$arr2
$arr1 = array(
0=>array('number'=>100,name=>'john'),
1=>array('number'=>200,name=>'johnny')
);
$arr2= array(
0=>array('number'=>300,name=>'r'),
1=>array('number'=>100,name=>'b'),
2=>array('number'=>200,name=>'c')
);
Final output should be an array like this
$arr1 = array(
0=>array('number'=>100,name=>'b'),
1=>array('number'=>200,name=>'c')
);
Any ideas to start off please ?
For specialized array modifications like this, the method of choice is array walk. It allows you to apply a custom function to each element in a given array.
Now, because of your data format, you will have to do a loop. Wrikken is asking if you can retrieve or transform the data to provide faster access. The algorithm below is O(n^2): it will require as many cycles as there are elements in the first array times the number of elements in the second array, or exactly count($arr1) * count($arr2).
function updateNameFromArray($element, $key, $arr2) {
foreach($arr2 as $value) {
if($value['number'] == $element['number']) {
$element['name'] == $value['name'];
break;
}
}
}
array_walk($arr1, "updateNameFromArray", $arr2);
Now, what Wrikken is suggesting is that if your arrays can be changed to be keyed on the 'number' property instead, then the search/replace operation is much easier. So if this were your data instead:
$arr1 = array(
100=>array('number'=>100,name=>'john'),
200=>array('number'=>200,name=>'johnny')
);
// notice the keys are 100 and 200 instead of 0,1
$arr2= array(
300=>array('number'=>300,name=>'r'),
100=>array('number'=>100,name=>'b'),
200=>array('number'=>200,name=>'c')
);
// notice the keys are 300, 100 and 200 instead of 0,1, 2
Then you could do this in O(n) time, with only looping over the first array.
foreach($arr1 as $key => $value) {
if(isset($arr2[$key])) {
$value['number'] = $arr2[$key]['number'];
}
}
Try this. It's not that clean but i think it would work.
<?php
$arr1 = array(0=>array('number'=>100,'name'=>'john'),1=>array('number'=>200,'name'=>'johnny'));
$arr2= array(0=>array('number'=>300,'name'=>'r'),1=>array('number'=>100,'name'=>'b'),2=>array('number'=>200,'name'=>'c'));
foreach( $arr1 as $key=>$data1 )
{
foreach( $arr2 as $key2=>$data2 )
{
if( $data1['number'] == $data2['number'] )
{
$arr1[$key]['name'] = $arr2[$key2]['name'];
}
}
}
print_r( $arr1 );
?>
the output would be :
Array
(
[0] => Array
(
[number] => 100
[name] => b
)
[1] => Array
(
[number] => 200
[name] => c
)
)
There isn't really a simple way for this to be accomplished with generic PHP functions, so, You might need to create mapping arrays.
The way I would approach this, is creating a loop that goes through the first array, and maps the number value as a key to the index of it's place in $arr1 giving you:
$tmp1 = array();
foreach ($arr1 as $key => $number_name) {
$tmp1[$number_name['number']] = $key;
}
This should give you an array that looks like
$tmp1 [
100 => 0,
200 => 1
];
Then I would loop through the second array, get the number value, if that existed as a key in $tmp1, get the associated value (being the key for $arr1), and use that to update the name in $arr1.
// Loop through $arr2
foreach ($arr2 as $number_name) {
// Get the number value
$number = $number_name['number'];
// Find the $arr1 index
if (isset($tmp1[$number])) {
$arr1_key = $tmp1[$number];
// Set the $arr1 name value
$arr1[$arr1_key]['name'] = $number_name['name'];
}
}
<?php
//Set the arrays
$arr1 = array(
array('number'=>100,'name'=>'john'),
array('number'=>200,'name'=>'johnny')
);
$arr2= array(
array('number'=>300,'name'=>'r'),
array('number'=>100,'name'=>'b'),
array('number'=>200,'name'=>'c')
);
// use a nested for loop to iterate and compare both arrays
for ($i=0;$i<count($arr1);$i++):
for ($j=0;$j<count($arr2);$j++):
if ($arr2[$j]['number']==$arr1[$i]['number'])
$arr1[$i]['name']=$arr2[$j]['name'];
endfor;
endfor;
print_r($arr1);
OUTPUT:
Array (
[0] => Array ( [number] => 100 [name] => b )
[1] => Array ( [number] => 200 [name] => c )
)
That being said, you should probably reconsider the very way your data is structured. Do you really need a multi-dimensional array or can you use a simple associative array, like so:
// set the arrays
$arr1 = array(
'john'=>100,
'johnny'=>200
);
$arr2 = array(
'r'=>300,
'b'=>100,
'c'=>200
);
// find values in arr2 common to both arrays
$arr3 = array_intersect($arr2, $arr1);
// change the key of arr1 to match the corresponding key in arr2
foreach ($arr3 as $key=>$value) {
$old_key = array_search($value, $arr1);
$arr1[$key]=$arr1[$old_key];
unset($arr1[$old_key]);
}
print_r($arr1);
OUTPUT:
Array (
[b] => 100
[c] => 200
)

Getting rid of duplicate array

Array is like this:
Array
(
[0] => 2011/10/05
)
Array
(
[0] => 2011/10/05
)
How can I get rid of the duplicate array?
php has a function
array_unique
http://php.net/manual/en/function.array-unique.php
EDIT
Option 1
<?php
$array1 = array("2011/10/05");
$array2 = array("2011/10/05");
$merged = $array1;
foreach($array2 as $v) array_push($merged,$v);
$unique = array_unique($merged);
?>
You could use array_merge, but the problem with array_merge is that it joins the same keys together which you probably don't want. The above code will add elements from array2 to array1 and then do array_unique (adding elements of array2 to array1 can also be done differently).
First merge and then unique
$a = array('2011/10/05');
$b = array('2011/10/05');
$c = array_merge($a,$b);
$d = array_unique($c);

Categories