I have two arrays that I need to match and post the result.
$arr1 = 1,3,4;
$arr2 = 1 => 'Title1'
2 => 'Title2'
3 => 'Title3'
4 => 'Title4'
I want to get the result to show the matched keys (number matches) to then show the value of $arr2
The above should result in Title1, Title3, title4
I have tried array_key_exists but i think im getting myself confused over something simple.
foreach($arr1 as $a)
{
if(array_key_exists($a, $arr2))
{
$new[$a] = $arr2[$a];
}
}
$l=1;
foreach($new as $n => $ob){
echo '<p>'.$new[$l][0].'">'.$new[$l][0].'</p>';
++$l;
}
In your case you can use like this
$arr1 = [1,3,4];
$arr2 = [1 => 'Title1', 2 => 'Title2', 3 => 'Title3', 4 => 'Title4'];
foreach($arr1 as $key){
echo "\n". $arr2[$key];
}
You can also check existence by isset first
Live demo : https://eval.in/720926
In your code, where does $d come from ? It should be $a.
And $n sould be used instead of $l (which is useless) and thus, not incremented.
To simplify your code, you could have written :
<?php
foreach($arr1 as $k){
if(array_key_exists($k, $arr2)){
// or : if(isset($arr2[$k])){
echo $arr2[$k] . "\n";
}
}
?>
Related
I have an associative array like this [this array is combination of two different arrays]:
I combine arrays and via array_combine() function
$products = array_combine($one_array_key,$second_array_values);
$products = array(
"arn1" =>"A",
"arn2" =>"A",
"arn3" =>"A",
"arn4" =>"B",
"arn5" =>"B",
"arn6" =>"B"
);
So As you can see there are two distinct values from array A and B.
I want two arrays consists of it's keys.
Or in other words: Compare values of associative array and matched values's key will be extract to the other array .
So My expected out is:
$A = array("arn1","arn2","arn3");
$B = array("arn4","arn5","arn6");
My code:
$products = array_combine($one_array_key,$second_array_values);
$products_distinct_values = array_count_values($product);
$products_distinct_values_keys = array_keys($products_distinct_values);
foreach ($products as $key => $value)
{
// what should I need write there, to get the x numbers of array(s), containing *key* of the same *value of array*
}
I SUPER would never use this "variable variables" technique in a professional project, but it does satisfy your brief. I will urge you to find the folly in your XY Problem.
Effectively, the snippet below will synchronously iterate over the two related input arrays and create variably-named result arrays to push values into.
Code: (Demo)
$one_array_key = ['A', 'A', 'A', 'B', 'B', 'B'];
$second_array_values = ['arn1', 'arn2', 'arn3', 'arn4', 'arn5', 'arn6'];
foreach ($one_array_key as $index => $value) {
$$value[] = $second_array_values[$index];
}
var_export($A);
echo "\n---\n";
var_export($B);
Output:
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
)
---
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
)
It makes much more sense to have a statically named variable containing keys and related subarrays. This way you can call array_keys() on the result, if you wish, to find out which groups were found in the original input.
Code: (Demo)
$result = [];
foreach ($one_array_key as $index => $value) {
$result[$value][] = $second_array_values[$index];
}
var_export($result);
Output:
array (
'A' =>
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
),
'B' =>
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
),
)
You can use the following PHP code to do that.
<?php
$products = array("arn1"=>"A", "arn2"=>"A", "arn3"=>"A", "arn4"=>"B", "arn5"=>"B", "arn6"=>"B");
$A = array();
$B = array();
foreach ($products as $key => $value)
{
if ($value == "A")
{
array_push ($A, $key);
}
else if ($value == "B")
{
array_push ($B, $key);
}
}
print_r ($A);
print_r ($B);
?>
Say i have two different arrays. I want to get each value from the first array, and add to it some values of each key in the second array. How do i do this please?
I tried using a foreach loop inside a foreach loop and for each value in the first array, it appends each value of the second array which isn't what i want
$array1 = array(chris, kate, john, jane);
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
foreach($array1 as $name){
foreach($array2 as $k => $v){
echo $name . "-" . $v;
}
}
I want my output to look like this
chris-1
kate-2
john-3
jane-4
Sometimes, the count of both array aren't the same. Some values in the first array produces an empty string, so in cases like that, it should just skip the value. Once the empty string in array1 is skipped or deleted, the count then matches array2
My above nested loop can't give me this. How do i go about this please?
Firstly I would use array_filter() to remove the empty strings from $array1:
$array1 = array(chris, kate, john, jane);
$array1 = array_filter($array1, function($value) {
return $value !== '';
});
Now we need to reindex the array to account for the gaps we made when removing empty strings.
$array1 = array_values($array1);
Considering you don't use the 'first', 'second', etc keys in $array2 for anything, we can just get rid of them using array_values(). This will leave us with an array like array(1,2,3,4) which will make accessing the data later on a little easier.
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
$array2 = array_values($array2);
Now we can loop through the first array and access the same position in the second array to create the final string.
// Assign the current element's numeric position to the $i variable on each iteration.
foreach($array1 as $i => $name){
echo $name . "-" . $array2[$i];
}
Final Code
$array1 = ['chris', 'kate', '', 'john', 'jane'];
$array1 = array_filter($array1, function ($value) {
return $value !== '';
});
$array1 = array_values($array1);
$array2 = ['first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4];
$array2 = array_values($array2);
foreach ($array1 as $i => $name) {
echo $name . "-" . $array2[$i];
}
I have 2 arrays:
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
and I echo the content of $array1 like
foreach ($array1 as $extra) {
echo $extra; }
What I am trying to do is to check every time before echoing the $extra whether the output is found in $array2. And if yes, to echo the value of the array2 instead.
So in my example above, instead of first second third fourth I want to echo hello bye see you fourth.
How can I do this?
You can do
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
print_r(array_intersect_key( $array2 ,array_flip($array1)));
Output
Array
(
[second] => bye
[first] => hello
[third] => see you
)
Sandbox
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
https://www.php.net/manual/en/function.array-intersect-key.php
And
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
https://www.php.net/manual/en/function.array-flip.php
Update
I know but it's array1 that is the "string". Array2 is the replacements. See the question: I want to echo hello bye see you fourth
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
echo implode(' ', array_intersect_key( array_merge(array_combine($array1,$array1), $array2) ,array_flip($array1)));
Output
hello bye see you fourth
Sandbox
The difference with this one is this bit
$array2 = array_merge(array_combine($array1,$array1), $array2)
What this does is make a new array with array_combine which has the same keys as values. In this case:
array('first'=>'first', 'second'=>'second', 'third'=>'third', 'fourth'=>'fourth')
Then we use the fact that when merging 2 rows the second array will overwrite keys from the first so we merge that with our original $array2
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fourth'=>'fourth', 'fifth' => 'good evening');
So by doing this "extra" step we insure that all elements in $array1 exist in $array2 - the order of $array1 is also preserved - in this case it just adds 'fourth'=>'fourth' but that is exactly what we need for the intersect to work.
Then we just implode it.
UPDATE2
This is a simpler one using preg_filter and preg_replace
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
echo implode(' ',preg_replace(preg_filter('/(.+)/', '/(\1)/i', array_keys($array2)), $array2, $array1));
Output
hello bye see you fourth
It's very similar to the str_replace one, so I didn't want to post it as it's own answer. But it does have a few benefits over str_replace. For example
echo implode(' ',preg_replace(preg_filter('/(.+)/', '/\b(\1)\b/i', array_keys($array2)), $array2, $array1));
Now we have \b word boundaries, which means first wont match firstone etc.
Sorry I really enjoy doing things like this, it's "fun" for me.
You can access $array2[$key] and use the null-coalescing operator since you apparently want to fall back to the value from $array1 if it doesn't exist as a key in $array2.
foreach ($array1 as $key) {
echo $array2[$key] ?? $key, ' ';
// [PHP5] echo isset($array2[$key]) ? $array2[$key] : $key, ' ';
}
Demo: https://3v4l.org/3vQYt
Note: this adds a potentially unwanted space at the end. If that's the case, either add a condition to the loop or do something like this instead:
echo implode(' ', array_map(function ($key) use ($array2) {
return $array2[$key] ?? $key;
// [PHP5] return isset($array2[$key]) ? $array2[$key] : $key;
}, $array1));
Demo: https://3v4l.org/VCDVt
foreach ($array1 as $extra) {
foreach ($array2 as $key=>$value) {
if($extra==$key){
echo $value;
}
}
}
something like this
Just use isset:
foreach($array1 as $e) {
$val = isset($array2[$e]) ? $array2[$e] : $e;
echo $val;
}
Doc can be found here: https://www.php.net/manual/en/function.isset.php
You can just implode the first array then use str_replace to replace the words from the second in the imploded string.
No need for loops in my opinion.
echo str_replace(array_keys($array2), $array2, implode(" ", $array1));
//hello bye see you fourth
Array_keys will take the keys from array2 and make them the find, then the values from array2 will be the replacements.
https://3v4l.org/UIWV0
I have two arrays and I want one, can I add array 2 to array one?
$array1 = array("Germany" => 2, "Belgium"=> 3);
$array2 = array("France" => 4, "Italy"=> 5);
$final_array = {both arrays in one};
is this possible?
Yes, use the array_merge function, like this:
$final_array = array_merge($array1, $array2);
print_r($final_array);
When I run the above script it'll output:
Array (
[Germany] => 2
[Belgium] => 3
[France] => 4
[Italy] => 5
)
Take a quick read here: http://www.php.net/manual/de/function.array-merge.php
Use array_merge like
$final_arr = array_merge($array1 , $array2);
print_r($final_arr);
See this LINK for more
I would like to mention that on duplicated keys array_merge() returns the value from the second array. So, if you have different values with same keys - you should write your own function.
For example:
<?php
$a = array('rund' => '2', 'group' => '3', 'kupon' => 'utre', 'tralala' => 'shtur_kupon');
$b = array('grund' => '2', 'group' => 'ww', 'soup' => '1', 'tralala' => 'fd');
function two_arrays_merge_all_values(array $a, array $b) {
foreach ($b as $b_key => $b_value) {
$a_last_index = count($a);
$current_index = 1;
foreach ($a as $a_key => $a_value) {
if ($a_key === $b_key) {
$unique = uniqid();
$a[$b_key . '_' . $unique] = $b[$b_key];
unset($b[$b_key]);
break;
}
if ($current_index == $a_last_index) {
$a[$b_key] = $b[$b_key];
unset($b[$b_key]);
}
$current_index++;
}
}
return $a;
}
This question already has answers here:
Get min and max value in PHP Array
(9 answers)
Closed 2 years ago.
The Problem
I have a multidimensional array similar to the one below. What I'm trying to achieve is a way to find and retrieve from the array the one with the highest "Total" value, now I know there's a function called max but that doesn't work with a multidimensional array like this.
What I've thought about doing is creating a foreach loop and building a new array with only the totals, then using max to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I'm not sure that's the most efficient way either.
Any ideas?
Array
(
[0] => Array
(
[Key1] => Key1
[Total] => 13
)
[1] => Array
(
[Key2] => Key2
[Total] => 117
)
[2] => Array
(
[Key3] => Key3
[Total] => 39
)
)
Since PHP 5.5 you can use array_column to get an array of values for specific key, and max it.
max(array_column($array, 'Total'))
Just do a simple loop and compare values or use array_reduce. # is an error suppressor; it hides the fact that $a['total'] is not declared before it is accessed on the first iteration. Demo
$data = array_reduce($data, function ($a, $b) {
return #$a['Total'] > $b['Total'] ? $a : $b ;
});
print_r($data);
// Array( [Key2] => Key2 [Total] => 117 )
It could also be written with arrow function syntax which has been avaiable since PHP7.4. Demo
var_export(
array_reduce(
$data,
fn($result, $row) =>
$result['Total'] > $row['Total']
? $result
: $row,
['Key1' => null, 'Total' => PHP_INT_MIN]
)
);
// array ('Key2' => 'Key2', 'Total' => 117,)
It's so basic algorithm.
$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;
foreach($arr as $k=>$v)
{
if($v['Total']>$max)
{
$max = $v['Total'];
$found_item = $v;
}
}
echo "max value is $max";
print_r($found_item);
Working demo
I know this question is old, but I'm providing the following answer in response to another question that pointed here after being marked as a duplicate. This is another alternative I don't see mentioned in the current answers.
I know there's a function called max but that doesn't work with a multidimensional array like this.
You can get around that with array_column which makes getting the maximum value very easy:
$arr = [['message_id' => 1,
'points' => 3],
['message_id' => 2,
'points' => 2],
['message_id' => 3,
'points' => 2]];
// max value
$max = max(array_column($arr, 'points'));
Getting the associative key is where it gets a little more tricky, considering that you might actually want multiple keys (if $max matches more than one value). You can do this with an anonymous function inside array_map, and use array_filter to remove the null values:
// keys of max value
$keys = array_filter(array_map(function ($arr) use ($max) {
return $arr['points'] == $max ? $arr['message_id'] : null;
}, $arr));
Output:
array(1) {
[0]=>
int(1)
}
If you do end up with multiples keys but are only interested in the first match found, then simply reference $keys[0].
another simple method will be
$max = array_map( function( $arr ) {
global $last;
return (int)( ( $arr["Total"] > $last ) ? $arr["Total"] : $last );
}, $array );
print_r( max( $max ) );
<?php
$myarray = array(
0 => array(
'Key1' => 'Key1',
'Total' => 13,
),
1 => array(
'Key2' => 'Key2',
'Total' => 117,
),
2 => array(
'Key2' => 'Key3',
'Total' => 39,
),
);
$out = array();
foreach ($myarray as $item) {
$out[] = $item['Total'];
}
echo max($out); //117
unset($out, $item);
Can be done using array_walk(array_walk_recursive if needed)
$arr is the array you want to search in
$largestElement = null;
array_walk($arr, function(&$item, $key) use (&$largestElement) {
if (!is_array($largestElement) || $largestElement["Total"] < $item["Total"]) {
$largestElement = $item;
}
});
You can use php usort function:
http://php.net/manual/en/function.usort.php
A pretty illustrative example is given here:
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
So it will sort the max value to the last array index.
Output:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
This example is given on aforementioned link
array_reduce accepts a 3rd "initial" parameter. Use this to avoid the bad practice of using "#" error suppression :
$data = array_reduce($data, function ($a, $b) {
return $a['Total'] > $b['Total'] ? $a : $b ;
},['Total' => 0]);
print_r($data);
PHP 7.4
$data = array_reduce($data, fn(a,b) => $a['Total'] > $b['Total'] ? $a : $b, ['Total' => 0]);