This question already has answers here:
How to filter an associative array comparing keys with values in an indexed array?
(12 answers)
Closed 3 years ago.
I have 2 arrays one is the collection of key and other with a collection of data ex.
$array1 = ['0'=>'A1','1'=>'A2','2'=>'A3'];
and
$array2 = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
I want data like this
$array = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3']
you can use array_filter for this:
$my_array = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
$allowed = ['0'=>'A1','1'=>'A2','2'=>'A3'];
$filtered = array_filter(
$my_array,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY
);
var_dump($filtered);
Output:
array(3) {
["A1"]=>
string(5) "Data1"
["A2"]=>
string(5) "Data2"
["A3"]=>
string(5) "Data3"
}
Demo: https://3v4l.org/ZvkJb
Credit: PHP: How to use array_filter() to filter array keys?
You can also try this one to get the exact data of $array2 as you mentioned in the question.
$array1 = ['0'=>'A1','1'=>'A2','2'=>'A3'];
$array2 = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
$ans = [];
foreach($array1 as $value)
{
if(isset($array2[$value]))
$ans[$value] = $array2[$value];
}
print_r($ans);
You can make $array1 a dic, then check if key in $array2 is set in the dic.
$array1 = array_flip($array1);
$result = [];
foreach($array2 as $k => $v){
if(isset($array1[$k])){
$result[$k] = $v;
}
}
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 5 months ago.
I want to loop for more than one array i was able to do for two using this code
$value=array_combine($val1,$val2);
foreach($value as $vl1=> $vl2)
Am now trying to do for more than two using this code but its not working
I don't know where am getting it wrong.
$value=array_combine($val1,$val2,$val3,$val4,$val5,val6);
foreach($value as $vl1=> $vl2,$vl3=> $vl4,$vl5=> $vl6 )
Thanks
Edited
Here's is the complete working code - Thanks to #Barmar
With this code, i was able to submit multiple columns and rows into the database.
if(isset($_POST['submit'])){
$head = $_POST['head'];
$surname = $_POST['surname'];
$othernames = $_POST['othernames'];
$affiliate_email = $_POST['affiliate_email'];
$affiliation = $_POST['affiliation'];
$phone_no = $_POST['phone_no'];
$value=array_combine($surname,$affiliate_email,$othernames,
$head,$affiliation,$phone_no);
foreach ($surname as $index => $sur) {
$affmail = $affiliate_email[$index];
$names = $othernames[$index];
$hd = $head[$index];
$affil = $affiliation[$index];
$phone = $phone_no[$index];
$page3="INSERT INTO tbl_name
(affiliate_email,surname,othernames,affiliation,phone_no,head) VALUES
'$affmail','$sur','$names','$affil','$phone','$hd')";
if(mysqli_query($db->connection, $page3)) {
header("location:page4?code=$app_code");
}
}
}
array_combine() can only take two arrays -- it creates an associative array that uses the first array as the keys, and the second array as the corresponding values. It makes no sense to give it more than 2 arrays, where would those elements go in this result?
Loop over one array, and use its index to access the other arrays.
foreach ($array1 as $index => $val1) {
$val2 = $array2[$index];
$val3 = $array3[$index];
...
}
What you are looking for is array_merge or array_merge_recursive depending on your actual array structure.
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.
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.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
Example
$arr1 = [1, 2, 3, 4, 5];
$arr2 = [6, 7, 8, 9, 10];
$arr3 = ['name' => 'Script47'];
$res = array_merge($arr1, $arr2, $arr3);
var_dump($res);
Output
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
["name"]=>
string(8) "Script47"
}
Thereafter, you can loop through the resultant array as a single using foreach($array as $key => $value) { }.
Live Example
Repl
Technically you can't loop over more then one "Thing" at a time.
But, if the arrays are correlated, (related). So say array1 => item1 is related to array2 => item1 is related to array3 => item1. Then I would suggest structuring your arrays like this:
Take this example
$array1 = [a1-item1,a1-item2,a1-item3];
$array2 = [a2-item1,a2-item2,a2-item3];
$array3 = [a3-item1,a3-item2,a3-item3];
And structure it like this (basically a matrix)
$combined1 = [
[a1-item1,a1-item2,a1-item3],
[a2-item1,a2-item2,a2-item3],
[a3-item1,a3-item2,a3-item3]
];
Then array_column(0) gives you all item1's, and $combined[0] gives you all of array1.
Conversely you can do it the opposite way too.
$combined2 = [
[a1-item1,a2-item1,a3-item1],
[a1-item2,a2-item2,a3-item2],
[a1-item3,a2-item3,a3-item3]
];
And then array_column(0) gives you array1, and $combined[0] gives you all of item 1's.
Which ever way makes more sense for what you are doing. The only difference is what you get in the foreach loop.
foreach($combined1 as $array){
print_r($array);
}
//Outputs: [a1-item1,a1-item2,a1-item3]
foreach($combined2 as $array){
print_r($array);
}
//Outputs: [a1-item1,a2-item1,a3-item1]
And then you can loop over it to your heart's content whichever way you want.
Then you could flip this middle one like
$combined1 = [
[a1-item1,a1-item2,a1-item3],
[a2-item3,a2-item2,a2-item1],
[a3-item1,a3-item2,a3-item3]
];
Just kidding, don't do that it will mess you all up... lol
Make sense.
Why it's not working
array_combine only accepts two arguments:
http://php.net/manual/en/function.array-combine.php
You can neither use foreach like that. You may only have one key and one value for each foreach, but you can use a foreach inside another foreach.
Something like array_combine with undefinable arguments number
Assuming that you really want to use that functionality, but with several arrays at the same time, you could implement something like this if you're using PHP 7 or a greater version:
<?php
function array_combine_many(array ...$keysAndValues)
{
$length = count($keysAndValues);
if ($length % 2 != 0) {
throw new \Error("The number of arguments should be even. It's: $length.");
}
$combinations = array();
for ($i = 0; $i < $length; ++$i) {
$combinations[] = array_combine(
$keysAndValues[$i],
$keysAndValues[++$i]
);
}
return $combinations;
}
If you're not using PHP 7 or a greater version, you have to use the func_get_args function:
<?php
function array_combine_many()
{
$keysAndValues = func_get_args();
$length = count($keysAndValues);
// etc...
foreach inside a foreach
You may use the implemented function like this:
<?php
$val1 = ['a', 'b', 'c'];
$val2 = ['12', '34', '56'];
$val3 = ['d', 'e', 'f', 'g'];
$val4 = ['156', '67', '5678', '346'];
$val5 = ['h'];
$val6 = ['3487'];
$combinations = array_combine_many($val1, $val2, $val3, $val4, $val5, $val6);
foreach ($combinations as $combination) {
foreach ($combination as $key => $val) {
echo "$key => $val\n";
}
}
Output:
a => 12
b => 34
c => 56
d => 156
e => 67
f => 5678
g => 346
h => 3487
Using array_map, array_merge and call_user_func_array
Here's another solution:
<?php
$merged = call_user_func_array(
'array_merge',
array_map(
function (array $args) {
return array_combine($args[0], $args[1]);
},
[
[$val1, $val2],
[$val3, $val4],
[$val5, $val6]
]
)
);
foreach ($merged as $key => $value) {
echo "$key => $value\n";
}
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I'm using a function called subval_sort to sort a multi-dimensional array.
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
$songs = array(
'1' => array('artist'=>'Bing Crosby', 'songname'=>'White Christmas'),
'2' => array('artist'=>'Elvis Presley', 'songname'=>'White Christmas'),
'3' => array('artist'=>'Abba', 'songname' =>'Waterloo')
);
$songs = subval_sort($songs,'songname');
print_r($songs);
Works fine. Now I want to sort by songname as first and artist as second. So: if two (or more) songname-values are the same I want to sort by artist. Like in SQL: ORDER BY songname, artist.
Do you have any ideas how to solve it?
You can use usort where you can define the custom comparison function
function cmp($a, $b)
{
if(strcmp($a['songname'], $b['songname'])) {
return strcmp($a['songname'], $b['songname']);
}
return strcmp($a["artist"], $b["artist"]);
}
implementation:
usort($songs, "cmp");
This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 8 years ago.
For example we have the following words: hey, hello, wrong
$unsorted = array("eyh", "lhleo", "nrwgo");
I know that I could use asort to sort the array alphabetically, but I don't want that.
I wish to take the elements of the array and sort those, so that it would become something like this:
$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted
hey sorted = ehy
hello sorted = ehllo
wrong sorted = gnorw
As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.
Thanks in advance!
function sort_each($arr) {
foreach ($arr as &$string) {
$stringParts = str_split($string);
sort($stringParts);
$string = implode('', $stringParts);
}
return $arr;
}
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )
$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
$myArray,
function (&$value) {
$value = str_split($value);
sort($value);
$value = implode($value);
}
);
print_r($myArray);
Try this
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString = implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);
pretty straightforward question actually..
is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?
I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?
function Combine($array1, $array2) {
if(count($array1) == count($array2)) {
$assArray = array();
for($i=0;$i<count($array1);$i++) {
$assArray[$array1[$i]] = $array2[$i];
}
return $assArray;
}
}
array_combine($keys, $values)
PS: Click on my answer! Its also a link!
you need array_combine.
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
There’s already an array_combine function:
$combined = array_combine($keys, $values);
hello everybody i will show you how to merge 2 arrays in one array
we have 2 arrays and i will make one array from them
$data_key = array('key1','key2');
$data_value = array('val1','val2');
lets declare the main array
$main_array = array();
now let's fill it with the 2 arrays
foreach ($data_key as $i => $key) {
$main_array[$key] = $data_value[$i];
}
now let's see the result by using var_dump($main_array);
array(2) {
["key1"]=> string(4) "val1"
["key2"]=> string(4) "val2"
}
i hope that can help someone :)