Array value matching - return keys - php

I have two arrays. The first one looks like:
Array1
(
[14] => foo
[15] => bar
[16] => hello
}
and the sencond looks like:
Array2
(
[Label1] => foo
[Label2] => bar
[Label3] => hello
[Label4] => foo
[Label5] => bar
}
I would like to compare the values of array1 against array2, if they match, I would like to return the corresponding key of array2.
Any help will be appreciated. Thanks

You can use array_intersect to get the intersection of both arrays:
$arr1 = array(
14=>'foo',
15=>'bar',
16=>'hello'
);
$arr2 = array(
'Label1'=>'foo',
'Label2'=>'bar',
'Label3'=>'hello',
'Label4'=>'foo',
'Label5'=>'bar'
);
var_dump(array_intersect($arr2, $arr1));
This returns:
array(5) {
["Label1"]=>
string(3) "foo"
["Label2"]=>
string(3) "bar"
["Label3"]=>
string(5) "hello"
["Label4"]=>
string(3) "foo"
["Label5"]=>
string(3) "bar"
}
To get the keys of this resulting array, use array_keys. And if you want to get only the first key of each duplicate value, send it through array_unique first:
var_dump(array_keys(array_unique(array_intersect($arr2, $arr1))));
This will get you:
array(3) {
[0]=>
string(6) "Label1"
[1]=>
string(6) "Label2"
[2]=>
string(6) "Label3"
}

You can always use the infamous brute-force "for" iteration:
This gets you all the keys of the values that match. To get just the very first one you would do a simple modification of this code.
PHP Code:
$arr1 = array(
14=>'foo',
15=>'bar',
16=>'hello'
);
$arr2 = array(
'Label1'=>'foo',
'Label2'=>'bar',
'Label3'=>'hello',
'Label4'=>'foo',
'Label5'=>'bar'
);
$results = array();
foreach($arr1 as $val)
foreach($arr2 as $key=>$val2)
if($val == $val2) array_push($results, $key);
// or to get just the first,
// replace the if statement with
//
// if($val == $val2) {
// $result = $key;
// break 2;
// }
print_r($results);
Result is:
array(3) {
[0] => "Label1",
[1] => "Label2",
[2] => "Label3"
}

You can go about like this:
$array1 = array(14 => "foo", 15 => "bar", 16 => "hello");
$array2 = array("Label1" => "foo", "Label2" => "bar", "Label3" => "hello", "Label4" => "foo", "Label5" => "bar", "Label5" => "test");
$result = array_intersect($array2, $array1);
echo '<pre>';
print_r($result);
Output:
Array
(
[Label1] => foo
[Label2] => bar
[Label3] => hello
[Label4] => foo
)
More Info:
array_intersect

You might want to check array_intersect_assoc
<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>
The above example will output:
Array
(
[a] => green
)

A simple loop will be much faster and cleaner than a cascade of built-in functions.
//$arr1, $arr2 as per Gumbo's answer...
$hash = array_flip($arr1);
$keys = array();
foreach($arr2 as $key => $val)
if(isset($hash[$val]))
$keys[] = $key;

Related

Reverse array elements with specific value

I have an array like this
$array = array( [0] => 'red1', [1] => 'blue1', [2] => 'red2', [3] => 'red3', [4] => 'blue2' );
A want to reverse order of elements with red value only so it looks like this:
$array = array( [0] => 'red3', [1] => 'blue1', [2] => 'red2', [3] => 'red1', [4] => 'blue2' );
I think a possible solution might be to:
Get all the values from the $array that you are looking for and
store them in an array $found
Reverse the values in $found keeping the keys
Replace the values in $array with the values from $found using
the key
For example:
$array = array(0 => 'red1', 1 => 'blue1', 2 => 'red2', 3 => 'red3', 4 => 'blue2');
// First get all the values with 'red' and store them in an array
$found = preg_grep('/red\d+/', $array);
// Reverse the values, keeping the keys
$found = array_combine(
array_keys($found),
array_reverse(
array_values($found)
)
);
// Then replace the values of $array with values having the same keys in $found
$array = array_replace($array, $found);
var_dump($array);
Will result in:
array(5) {
[0]=>
string(4) "red3"
[1]=>
string(5) "blue1"
[2]=>
string(4) "red2"
[3]=>
string(4) "red1"
[4]=>
string(5) "blue2"
}
You can catch red's quote to a new array and sort them.
<?php
$arr = array(
'red1',
'blue1',
'red2',
'red3',
'blue2'
);
$sortArr = array();
for ($i=0; $i < sizeof($arr); $i++) {
if(strstr($arr[$i], "red")){
$sortArr[] = &$arr[$i];
}
}
?>
I think you can do using searching specific words by strpos and sorting array by ksort (sort associative arrays in ascending order, according to the key)
foreach ($array as $key => $value) {
if(strpos($value,"red") !== false){
($key === 0) ? $index = 3 : (($key === 3) ? $index = 0 : $index = 2);
$temp[$index] = $value;
}
else {
$temp[$key] = $value;
}
}
ksort($temp);
var_dump($temp);
[But It will not work in larger array than this]

How to merge Arrays in php

How to merge many Arrays in php
$array1="Array ( [0] => mouse ) Array ( [0] => mac ) Array ( [0] => keyboard )";
how i can array like this
Array( [0] =>mouse [1] => mac [2] =>keyboard );
depending on how your arrays are being stored, there are a couple of options.
Here are 2 examples:
<?php
$old_array = array(
array('mouse'),
array('mac'),
array('keyboard')
);
$new_array = array();
foreach($old_array as $a){
$new_array[] = $a[0];
}
echo '<pre>',print_r($new_array),'</pre>';
//// OR ////
$array1 = array('mouse');
$array2 = array('mac');
$array3 = array('keyboard');
$new_array = array_merge($array1,$array2,$array3);
echo '<pre>',print_r($new_array),'</pre>';
You should use array_merge function of PHP.
This:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
will return this:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
It's as easy as a piece of cake! :)
Try it: http://www.w3schools.com/php/showphp.asp?filename=demo_func_array_merge
Tutorials:
http://www.w3schools.com/php/func_array_merge.asp
http://php.net/array_merge
So you basically have an array of arrays. You can do this in the following way:
$array = array(array(0 => 'mouse'), array(1 => 'mac'), array(2 => 'keyboard'));
$mergedArray = array();
foreach ($array as $part) {
$mergedArray = array_merge($mergedArray, $part);
}
var_dump($mergedArray);
The result is exactly what you would expect:
array(3) {
[0]=>
string(5) "mouse"
[1]=>
string(3) "mac"
[2]=>
string(8) "keyboard"
}
If you also have scalars in the big array, you can modify the loop to the following:
foreach ($array as $part) {
if (!is_array($part)) {
$mergedArray[] = $part;
} else {
$mergedArray = array_merge($mergedArray, $part);
}
}
Note: This will merge all values from all sub arrays, it's not limited to one entry per sub array.
php array_merge() function, 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.
Merge N number of array using $array = array_merge( $array1 , $array2, $array3 ..... $arrayN);
$array1 = array ( '0' => 'mouse' );
$array2 = array ( '0' => 'mac' );
$array3 = array ( '0' => 'keyboard' );
$array = array_merge( $array1 , $array2, $array3);
echo "<pre>";
print_r($array);
echo "</pre>";
O/P:
Array
(
[0] => mouse
[1] => mac
[2] => keyboard
)
More info: http://us2.php.net/array_merge

Merging two arrays without changing key values php

I have two arrays in php as shown in the code
<?php
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
print_r(array_merge($a[0],$b[0]));
?>
I need to merge two arrays. array_merge function successfully merged two of them but key value gets changed. I need the following output
Array
(
[0]=>Array(
[500] => 1
[502] => 2
[503] => 3
[504] => 5
)
)
What function can I use in php so that the following output is obtained without changing key values?
From the documentation, Example #3:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
Therefore, try: $a[0] + $b[0]
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a + $b; //$c will be a merged array
see the answer for this question
Try:
$final = array();
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
foreach( $a as $key=>$each ){
$final[$key] = $each;
}
foreach( $b as $key=>$each ){
$final[$key] = $each;
}
print_r( $final );
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a[0] + $b[0];
print_r($c);
Will print:
Array ( [500] => 1 [502] => 2 [503] => 3 [504] => 5 )
Just write :
<?php
$a = array(2=>'green', 4=>'red', 7=>'yellow',3=>'Green');
$b = array(8=>'avocado');
$d = $a+$b;
echo'<pre>'; print_r($d);
?>
out put :
Array
(
[2] => green
[4] => red
[7] => yellow
[3] => Green
[8] => avocado
)

How to Re-structure multi-dimensional array in PHP?

I have an array that looks like this:
array(3) {
[0]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(5) "3238"
}
[1]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
[2]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
I would like to write a foreach loop that would turn this array into:
array(2) {
[0]=>
array(1) {
"2012-11-14" => "3238"
}
[1]=>
array(1) {
"2012-11-13" => "3231"
}
So, basically, I would like to use the array element formatted as Y-M-D date as key to the second element in the array.
Given the following array...
$array = array(
0 => array(0 => "2012-11-14", 1 => "3238"),
1 => array(0 => "2012-11-13", 1 => "3231"),
2 => array(0 => "2012-11-13", 1 => "3231"),
);
putting it into a new array like this:
$new_array = array();
foreach ($array as $key => $item)
{
$new_array[$key][$item[0]] = $item[1];
}
print_r($new_array);
produces this output:
Array
(
[0] => Array
(
[2012-11-14] => 3238
)
[1] => Array
(
[2012-11-13] => 3231
)
[2] => Array
(
[2012-11-13] => 3231
)
)
My answer doesn't get rid of the duplicates, but the added dimension as specified in the original question means that duplicate dates as keys aren't an issue.
<?php
$data = array(
array("2012-11-14", "3238"),
array("2012-11-13", "3231"),
array("2012-11-13", "3231") // warning! when there are two record with same date, the second's count will be display
);
$result = array();
foreach ($data as $value) {
$result[$value[0]] = $value[1];
}
echo '<pre>';
print_r($result);
<?php
$newArray = array();
for($i=0;$i<count($arrayVariable);$i++)
{
$newArray[$arrayVariable[$i][0]] = $arrayVariable[$i][1];
}
echo '<pre>';print_r($newArray);echo '</pre>';
?>
Didn't test it but something like this should work in concept. Of course change arrayVariable to your variable.. but that aside.
You can use this code to get what you want:
$dates = array(
array("2012-11-01", "3238"),
array("2012-11-03", "4321")
);
print_r($dates);
$result = array();
foreach($dates as $value) {
$result[][$value[0]] = $value[1];
}
print_r($result);
The output will look like the requested form:
Array
(
[0] => Array
(
[2012-11-01] => 3238
)
[1] => Array
(
[2012-11-03] => 4321
)
)
Codepad demo: http://codepad.org/XAmUEdYh
However, I would personally prefer Aykut's solution. You would of course have a problem when you've got two records with the same date, but the overall array layout is a bit nicer ;).
Here is what I came up with:
<?php
$original = array(
array(
"2012-11-14",
"3238"
),
array(
"2012-11-13",
"3231"
),
array(
"2012-11-13",
"3231"
)
);
$newArray = array();
foreach($original as $subArray){
$newArray[] = array($subArray[0] => $subArray[1]);
}
var_dump($newArray);

How do I flatten an associative array into an array with only values in PHP?

I have an array that has keys and values. For eg:
Array (
[name] => aalaap
[age] => 29
[location] => mumbai
)
I want to convert the keys from this into values, but I want the values to apear right after the keys. For eg:
Array (
[0] => name
[1] => aalaap
[2] => age
[3] => 29
[4] => location
[5] => mumbai
)
I can easily write an iteration function that will do this... for eg:
array_flatten($arr) {
foreach ($arr as $arrkey => $arrval) {
$arr_new[] = $arrkey;
$arr_new[] = $arrval;
}
return $arr_new;
}
...but I'm trying to find out if there's any way this can be accomplished using array_combine, array_keys, array_values and/or array_merge, preferably in one, so i don't need to use a custom function.
Is there?
Your own solution is probably the cleanest solution, so converting it to a "one-liner":
$array = array('name' => 'aalaap','age' => 29, 'location' => 'mumbai');
$answer = array();
array_walk($array, create_function('$val,$key', 'global $answer; $answer[]=$key; $answer[]=$val;'));
var_dump($answer);
This avoids unnecessary and expensive array copies or sorting.
Alternatively, lose the global:
array_walk($array, create_function('$val,$key,$result', '$result[]=$key; $result[]=$val;'), &$answer);
I don't think this is possible - with the built-in functions you'll end up with all the keys then all the values:
$a = array('a' => 'A', 'b' => 'B', 'c' => 'C');
$a = array_merge(array_keys($a), array_values($a));
print_r($a);
You're going to have to use a loop like this:
$b = array();
foreach ($a as $key => $value)
{
$b[] = $key;
$b[] = $value;
}
PHP 5.3+ version of Just Jules' answer, and a bit more readable:
array_walk($array, function($val, $key) use (&$answer) {
$answer[] = $key;
$answer[] = $val;
});
It is possible, but I don't think it is more readable or any faster. It would work with a less-known feature of PHP - the array addition:
$array = array('name' => 'aalaap', 'age' => 29, 'location' => 'mumbai');
# Separate keys and values into distinct arrays
$keys = array_keys($array);
$values = array_values($array);
# Generate 2 new array containing indexes for the 2 arrays which contain
# only odd/even numbers:
$keysKeys = range(0, count($keys) * 2 - 1, 2);
$valuesKeys = range(1, count($keys) * 2, 2);
# Combine the keys with the values and add the results:
$array = array_combine($keysKeys, $keys) + array_combine($valuesKeys, $values);
# Sort the resulting array, otherwise the numbering will be broken
# (1,3,5,2,4,6)
ksort($array);
# Result:
var_dump($array);
array(6) {
[0]=>
string(4) "name"
[1]=>
string(6) "aalaap"
[2]=>
string(3) "age"
[3]=>
int(29)
[4]=>
string(8) "location"
[5]=>
string(6) "mumbai"
}
Could use an array_reduce to get close.
array_reduce(array_keys($arr), function($carry, $key)use($arr){
$carry[] = $key;
$carry[] = $arr[$key];
return $carry;
}, array());

Categories