Laravel/PHP add keys to values - php

I have an array like so:
[5, 2, 9]
However, I need this array:
[0 => 5, 1 => 2, 2 => 9]
So I need the index as key. Is there a function to achieve this? Now I create an empty array manually and I use array_push through a foreach loop. It works, however this doesn't seem elegant.
Is there a better solution?

$array = [5, 2, 9];
print_r($array);
outputs:
Array
(
[0] => 5
[1] => 2
[2] => 9
)

if you print array in loop you can see default key
$arr=[5, 2, 9];
foreach($arr as $key=>$val){
echo 'Key='.$key.','.'val='.$val.'<br/>';
}
OUTPUT
Key=0,val=5
Key=1,val=2
Key=2,val=9
Also if you echo using key like
$arr=[5, 2, 9];
echo $arr[1];
output
2

Use array_combine,
At first, create an array of values,
$values = array(5, 2, 9);
Now, create an array of keys,
$keys = array(0, 1, 2);
After that, Combine two array to get result,
$result = array_combine ( array $keys , array $values );

Your array already has the keys based off its position in the array
$test = [5, 2, 9];
print_r($test);
Array ( [0] => 5 [1] => 2 [3] => 9 )
echo $test[0]; = 5
echo $test[1]; = 2
echo $test[3]; = 9

Related

Two same length array into find sum of value second array element value for first array element value wise in php

I have two arrays. They are always the same length. If the first array element value is the same then sum of the second array element value.
Example
$array1 = array(1,2,2,3);
$array2 = array(10,20,30,50);
// I can get the sum of array1 and array2 output.
$array_sum1 = array(10,50,50);
$array3 = array(4,4,4,6);
$array4 = array(10,20,30,50);
// I can get the sum of array3 and array4 output.
$array_sum2 = array(60,50);
How do I go about achieving this?
You can use array_sum with array_map like below,
$array1 = [1, 2, 2, 3];
$array2 = [10, 20, 30, 50];
$array_sum1 = [];
foreach ($array1 as $key => $value) {
$array_sum1[$value][] = $array2[$key];
}
$array_sum1 = array_map("array_sum", $array_sum1);
print_r($array_sum1);
$array3 = [4, 4, 4, 6];
$array4 = [10, 20, 30, 50];
$array_sum2 = [];
foreach ($array3 as $key => $value) {
$array_sum2[$value][] = $array4[$key];
}
$array_sum2 = array_map("array_sum", $array_sum2);
print_r($array_sum2);die;
Demo
Output:-
Array
(
[1] => 10
[2] => 50
[3] => 50
)
Array
(
[4] => 60
[6] => 50
)
It is indirect to perform two iterations of your data to group & sum.
Use the "id" values as keys in your output array. If a given "id" is encountered for the first time, then save the "val" value to the "id"; after the first encounter, add the "val" to the "id".
Code: (Demo)
$ids = [1, 2, 2, 3];
$vals = [10, 20, 30, 50];
foreach ($ids as $index => $id) {
if (!isset($result[$id])) {
$result[$id] = $vals[$index];
} else {
$result[$id] += $vals[$index];
}
}
var_export($result);
Output:
array (
1 => 10,
2 => 50,
3 => 50,
)
Here are similar (near duplicate) answers:
https://stackoverflow.com/a/53141488/2943403
https://stackoverflow.com/a/52485161/2943403
https://stackoverflow.com/a/47926978/2943403
https://stackoverflow.com/a/54421292/2943403

Need to get unique values in array

Array
(
)
Array
(
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
[1] => 12
)
I want this array
Array
(
[0] => 14
[1] => 12
)
Here is my code:
$colorarray = array();
foreach($catIds as $catid){
$colorarray[] = $catid;
}
Need to get unique array values
Thanks
You can use call_user_func_array with array-merge for flatten your array and then use array-unique as:
$res = call_user_func_array('array_merge', $arr);
print_r(array_unique($res)); // will give 12 and 14
Live example 3v4l
Or as #Progrock suggested: $output = array_unique(array_merge(...$data)); (I like that syntax using the ...)
You can always do something like this:
$colorarray = array();
foreach($catIds as $catid){
if(!in_array($catid, $colorarray) {
$colorarray[] = $catid;
}
}
But also this has n*n complexity, So if your array is way too big, it might not be the most optimised solution for you.
You can do following to generate unique array.
array_unique($YOUR_ARRAY_VARIABLE, SORT_REGULAR);
this way only unique value is there in your array instead of duplication.
UPDATED
This is also one way to do same
<?php
// define array
$a = array(1, 5, 2, 5, 1, 3, 2, 4, 5);
// print original array
echo "Original Array : \n";
print_r($a);
// remove duplicate values by using
// flipping keys and values
$a = array_flip($a);
// restore the array elements by again
// flipping keys and values.
$a = array_flip($a);
// re-order the array keys
$a= array_values($a);
// print updated array
echo "\nUpdated Array : \n ";
print_r($a);
?>
Reference link
Hope this will helps you
I have updated your code please check
$colorarray = array();
foreach($catIds as $catid){
$colorarray[$catid] = $catid;
}
This will give you 100% unique values.
PHP: Removes duplicate values from an array
<?php
$fruits_list = array('Orange', 'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
------your case--------
$result = array_unique($catIds);
print_r($result);
You can construct a new array of all values by looping through each sub-array of the original, and then filter the result with array_unique:
<?php
$data =
[
[
0=>13
],
[
0=>13
],
[
0=>17,
1=>19
]
];
foreach($data as $array)
foreach($array as $v)
$all_values[] = $v;
var_export($all_values);
$unique = array_unique($all_values);
var_export($unique);
Output:
array (
0 => 13,
1 => 13,
2 => 17,
3 => 19,
)array (
0 => 13,
2 => 17,
3 => 19,
)

Make new array values from element value plus the previous element's value

I have array like this :
$array = array(1, 4, 8, 3, 7);
I want sum the value of array but first, I unshift the array like this :
<?php
$array = array(1, 4, 8, 3, 7);
array_unshift($array, 0);
array_pop($array);
foreach($array as $key => $val) {
echo $val;
}
?>
then I want sum array first (1, 4, 8, 3, 7) with new array (0, 1, 4, 8, 3)
sum like 1 plus 0 and 4 plus 1 and 8 plus 4 etc
And I want the output is : 1, 5, 12, 11, 10
Just use array_map.
array_map allows you to use a custom function on multiple arrays at the same time
$array = array(1, 4, 8, 3, 7);
$others = $array;
array_unshift($others, 0);
array_pop($others);
function sumarray($v1,$v2){
return $v1+$v2;
}
$res = array_map('sumarray', $array,$others);
print_r($res);
result like
Array
(
[0] => 1
[1] => 5
[2] => 12
[3] => 11
[4] => 10
)
You can use for loop instead of foreach.
Example
$array = $array2 = array(1, 4, 8, 3, 7);
array_unshift($array, 0);
array_pop($array);
$array3 = [];
for($i = 0; $i < count($array); $i++) {
$array3[] = $array[$i]+$array2[$i];
}
print_r($array3);
Output
Array
(
[0] => 1
[1] => 5
[2] => 12
[3] => 11
[4] => 10
)
You can store the popped value in a variable (popped) so you can use it later. Then you can use a regular for loop to loop over your array and add the popped value to the array once the loop is complete:
$array = array(1, 4, 8, 3, 7);
array_unshift($array, 0);
$popped = array_pop($array);
$result = [];
for($i = 0; $i < count($array)-1; $i++) {
$val1 = $array[$i];
$val2 = $array[$i + 1];
$result[] = $val1 + $val2;
}
$result[] = end($array) + $popped; // add the last element with the popped value
print_r($result);
Output:
Array ( [0] => 1 [1] => 5 [2] => 12 [3] => 11 [4] => 10 )
There is no need to pop or shift any elements and there is no need to create a copy of the input array.
As you iterate the input array, sum the current value with the previous value. If there is no previous value, use zero. This is exceedingly simple since your input is an indexed array.
Code: (Demo)
$array = [1, 4, 8, 3, 7];
$result = [];
foreach ($array as $index => $value) {
$result[] = $value + ($array[$index - 1] ?? 0);
}
var_export($result);
// [1, 5, 12, 11, 10]

How can I find the Nth most common value in a PHP array?

I have an array like the one below:
$array = Array(1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5 ,5, 5, 6, 7, 8);
I know I can easily find the most repeated value in this array with a procedure like that one:
$array = Array(1, 2, 2, 2, 3, 3);
$counts = array_count_values($array);
arsort($counts);
echo key($counts);
But how can I find the second most repeated value? Or the third? Or the fourth and beyond?
In short your question boils down to: how to get the nth key from an array?
Like this:
echo array_keys($counts)[1];
For ancient PHP versions which don't support this syntax:
$keys = array_keys($counts);
echo $keys[1];
By sorting and displaying the whole array you can get them in order:
$array = Array(1, 2, 2, 2, 3, 3);
$counts = array_count_values($array);
arsort($counts);
echo '<pre>';
print_r($counts);
Returns:
Array
(
[2] => 3
[3] => 2
[1] => 1
)
Each subsequent element in the array would have the values as keys in descending order of their appearance in the array.

PHP - If any array values match then remove all of them

I'm kind of stuck here on what I think must have quite a simple solution.
Say I have an array:
$A = array(1, 1, 2, 4, 6, 7, 7, 7, 13);
How could I possibly remove all of the values that occur more than once?
So I'm left with an array that looks like this
$A = array(2, 4, 6, 13);
I've tried using array unique, but that just removes duplicates leaving you with a single value. I need to use the following logic: if there are any values that match - then remove all of the values that match.
You could always try something like this.
$A = array(1, 1, 2, 4, 6, 7, 7, 7, 13);
$A = array_count_values($A);
foreach($A as $key => $value) {
if($value > 1)
unset($A[$key]);
}
$A = array_keys($A);
print_r($A);
edit: fixed error
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 13
)
You can use array_filter() with a custom callback to filter out the array values which repeat more than once:
function removeDuplicates($array) {
$values = array_count_values($array);
return array_filter($array, function($item) use ($values) {
return $values[$item] === 1;
});
}
Usage:
$A = array(1, 1, 2, 4, 6, 7, 7, 7, 13);
print_r( removeDuplicates($A) );
Output:
Array
(
[2] => 2
[3] => 4
[4] => 6
[8] => 13
)
Demo.
You can do this with abit of coding.
First see this SO post to get a list of all the duplicates using array_unique:
php return only duplicated entries from an array
Then you'll have to loop through the duplicates returned from the link above and do an array_search to return the index of the values and then array_splice to actually remove it.
I don't know of any code that will do this in one step for you.
Try this (with PHP >= 5.3):
$A = array_keys(array_filter(
array_count_values($A),
function ($count)
{
return $count == 1;
}
));
Explanation:
array_count_values returns an array using the values of array as keys and their frequency in array as values.
array_filter Iterates over each value in the array passing them to the callback function (in this case anonymous function) . If the frequency is 1, the current value from array is returned into the result array.
array_keys returns the keys from the array, in this case the values with frequency equal to 1.
So, the compressed "one-line" form is:
$A=array_keys(array_filter(array_count_values($A),function($c){return $c==1;}));

Categories