PHP finding the first matching value in 2 arrays - php

I have two arrays and want to find the first match for either of arrayTwos values in arrayOne.
arrayOne ( [0] = C [1] = A [2] = B [3] = D [4] = B [5] = C)
and
arrayTwo ( [0] = A [1] = B [2] = C )
With these values I would want to return the value "C" as it is the first value in arrayTwo to appear in arrayOne.
I'm thinking I could use for loops and if statements to run through but re there any functions in PHP I could use to simplify this?

Use array_search
$keys = array_search($second_array, $first_array);
Ref : http://in3.php.net/array_search

array_search
$valuekeys = array_search($secondarray, $arrayone);

use array_intersect
$arrayOne = array('C', 'A', 'B', 'D', 'B', 'C');
$arrayTwo = array('A', 'C');
$result = array_intersect($arrayOne , $arrayTwo);
echo $result[0];

Use array_intersect. This will do the job. http://www.php.net/manual/en/function.array-intersect.php Note the difference between using array_intersect($array1, $array2) and array_intersect($array2, $array1)

You can use array_intersect():
$arr1 = array( 0 => 'C', 1 => 'A', 2 => 'B', 3 => 'D', 4 => 'B', 5 => 'C');
$arr2 = array( 0 => 'A', 1 => 'B', '2' => 'C' );
$arr3 = array_intersect($arr1,$arr2);
var_dump($arr3[0]);
string(1) "C"

Related

PHP Sorting by turns

I want to sort the following data items in the order they are presented below :
$char = array('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C');
And i want the output is :
$char = array('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C');
Any tricks to make it sort with PHP
Many Thanks!
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Try this:
$char = array('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C');
sort($char);
print_r($char);
Credit: here
In order to sort an array in the Ascending order of the values you can use the asort() so that it sorts the array in ascending order of the values.
asort — Sort an array and maintain index association.
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Example Code:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
Output:
c = apple
b = banana
d = lemon
a = orange
Example Reference: asort
Solution to your Question
Your Code needs to be like this.
<?php
$char = array('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C');
asort($char);//Sorts the array here
foreach ($char as $key => $val) {
$values[] = $val;
}
print_r($values);//Print the sorted output
?>
Output:
Array ( [0] => A [1] => A [2] => A [3] => A [4] => A [5] => B [6] => B [7] => B [8] => B [9] => B [10] => C [11] => C [12] => C [13] => C [14] => C )

How to transform a string that contains a nested array into an actual array?

I am trying to find a way to transform a string type variable into an array type variable. To be more precise, what i am looking for is the change this (example):
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
note that this is not a json-formatted string.
into this:
$v = ['1', 'a', ['2', 'b', ['3'], 'c']];
Note the double-quotes in the first example, $v is a string, not an array, which is the desired effect.
Simple solution using str_replace(to prepare for decoding) and json_decode functions:
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$converted = json_decode(str_replace("'",'"',$v));
print_r($converted);
The output:
Array
(
[0] => 1
[1] => a
[2] => Array
(
[0] => 2
[1] => b
[2] => Array
(
[0] => 3
)
[3] => c
)
)
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
eval("\$v = $v;");
var_dump($v);
PS: make sure $v string doesn't contain unexpected code.
This should work:
$json = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$json = str_replace("'",'"',$json);
$result_array = json_decode($json); // This is your array

PHP Assign Array Keys with New Array with Existing Arrays

To save on typing out the key name for every single array, I want to be able to build lists like..
$lists = array (
0 => array ('A', 'B', 'C', 'D', 'E');
1 => array ('A', 'B', 'C', 'D', 'E');
2 => array ('A', 'B', 'C', 'D', 'E');
)
.. and then assign the same key names to all them (either before or after)..
Key1, Key2, Key3, Key4, Key5
.. so when they're called, I can do something like..
foreach($lists as $list) {
showList($list);
}
.. and then within the showList() function, I can call the 5 keys by the key name.
The function I have set no problem, but it's assigning the key names that I'm not sure how to do. Sorry if my terminology isn't accurate, but hopefully I explained it well enough.
array_combine will make an associative array from an array of keys and an array of values.
$keys = array('Key1', 'Key2', 'Key3', 'Key4', 'Key5');
foreach ($lists as $list) {
showList(array_combine($keys, $list));
}
If you want to modify $lists permanently, you can do:
foreach ($lists as &$list) {
$list = array_combine($keys, $list);
}
The reference variable &$list makes this replace the elements in place.
Try this :
<?php
$keys = array('Key1', 'Key2', 'Key3', 'Key4', 'Key5');
$lists = array (
array ('A', 'B', 'C', 'D', 'E'),
array ('A', 'B', 'C', 'D', 'E'),
array ('A', 'B', 'C', 'D', 'E')
);
function showList($list){
global $keys;
return array_combine($keys, $list);
}
$output = array_map("showList", $lists);
echo "<pre>";
print_r($output);
?>
Result:
Array
(
[0] => Array
(
[Key1] => A
[Key2] => B
[Key3] => C
[Key4] => D
[Key5] => E
)
[1] => Array
(
[Key1] => A
[Key2] => B
[Key3] => C
[Key4] => D
[Key5] => E
)
[2] => Array
(
[Key1] => A
[Key2] => B
[Key3] => C
[Key4] => D
[Key5] => E
)
)

How to Extract and combine array from array

I have print_r result like this :
Array
(
[0] => A, B, C, D
[1] => 15,20,24,19
)
how to make them like this :
Array
(
[A] => 15
[B] => 20
[C] => 24
[D] => 19
)
Great thanks for help :)
Try this:
$a = array('A', 'B', 'C', 'D');
$b = array(15, 20, 24, 19);
$c = array();
foreach ($a as $index => $value) {
if (isset($b[$index])) {
$c[$value] = $b[$index];
}
}
var_dump($c);
You need explode() and array_combine(). Assuming your initial array, $arr:
$new_arr = array_combine(explode(', ', $arr[0]), explode(',', $arr[1]));
See demo
Try to explode() your array index by comma and combine both array with keys and values using array_combine()
$a = explode(',',$arr[0]);
$b = explode(',',$arr[1]);
$new = array_combine($a,$b);
print_r($new); //Array ( [A] => 15 [ B] => 20 [ C] => 24 [ D] => 19 )
array_combine is the way
<?php
$myArray = array(
array('A', 'B', 'C', 'D'),
array(15, 20, 24, 19)
);
$combinedArray = array_combine($myArray[0], $myArray[1]);

PHP - merge values of arrays where previous array has missing or present but empty values

How can I merge two arrays:
$arr1 = [1 => 'a', 2 => '', 3 => 'c'];
$arr2 = [1 => 'd', 2 => 'e', 3 => 'f'];
and get:
[1 => 'a', 2 => 'e', 3 => 'c'];
I have done it succesfully with:
$arr1 = [1 => 'a', 3 => 'c'];
$arr2 = [1 => 'd', 2 => 'e', 3 => 'f'];
$arr1 + $arr2;
But, sometimes $arr1 also contains value 2 => '' which is empty but present and in this case key 2 will not be overwriten by $arr2.
Use
$arr1 = array(1 => 'a', 2 => '', 3 => 'c');
$arr2 = array(1 => 'd', 2 => 'e', 3 => 'f');
$arr3 = array_filter($arr1) + array_filter($arr2);
print_r($arr3);
$arr1 = array("a","","c");
$arr2 = array("d","e","f");
$i = 0;
foreach ($arr1 as $value) {
if($arr1[$i] == "")
$arr1[$i] = $arr2[$i];
$i++;
}
print_r($arr1);
Here matrices must be equal in dimension and the number of elements

Categories