How to group foreach result the same value PHP - php

Please help me on how to group the value from foreach result:
foreach ($result as $value) {
$group = $value['Barcode'];
echo $group.'<br>';
}
the result of this:
9822550005004
9822550005004
9844660005002
9844660005002
9844660005002
9844660005002
My expected result would be:
9822550005004
9844660005002

You can use foreach and external array for getting the output like you want.
Using the foreach loop you need to store the each value in an array, here i store the value to the $arr array and makes the key as same as the value, cause yuo need the unique values, after storing the values just implode them with suitable delimiter space and get the desire output.
$arr = array();
foreach($result as $value){
$arr[$value['Barcode']] = $value['Barcode'];
}
echo implode(" ", $arr); //9822550005004 9844660005002
Using Array functions...
array_column Get all the columns from the array as name Barcode and makes anther array of them, After that array_unique choose the unique values from the returned array and also make another array of it. So now you need to implode them as you want. The implode method makes the array as string with a delimiter. Here i use space.
$arr = array_unique(array_column($result, "Barcode"));
echo implode(" ", $arr); //9822550005004 9844660005002

Related

How to use str_repeat to repeat a string from an array giving an index of each loop of the str_repeat [duplicate]

This question already has answers here:
How do I create a comma-separated list from an array in PHP?
(11 answers)
Closed 2 years ago.
I'm trying to concatenate array keys (which are originally a class properties). So what I did is:
echo '<pre>'.print_r(array_keys(get_object_vars($addressPark)),TRUE).'</pre>';
Outputs:
Array
(
[0] => streetAddress_1
[1] => street_address_2
[2] => city_name
[3] => subdivision_name
[4] => country_name
)
This is how I get the AddressPark object's properties names.
$arr = array_keys(get_object_vars($addressPark));
$count = count($arr);
I want to access the object properties by index, that is why I used array_keys.
$props = str_repeat("{$arr[$count-$count]},",$count-2).$arr[$count-1];
echo $props;
The results is:
streetAddress_1,streetAddress_1,streetAddress_1,country_name
It repeats $arr[0] = 'streetAddress_1' which is normal because in every loop of the str_repeat the index of $arr is $count-$count = 0.
So what I exactly want str_repeat to do is for each loop it goes like: $count-($count-0),$count-($count-1) ... $count-($count-4). Without using any other loop to increment the value from (0 to 4).
So is there another way to do it?
No, you cannot use str_repeat function directly to copy each of the values out of an array into a string. However there are many ways to achieve this, with the most popular being the implode() and array_keys functions.
array_keys extracts the keys from the array. The following examples will solely concentrate on the other part of the issue which is to concatenate the values of the array.
Implode
implode: Join array elements with a string
string implode ( string $glue , array $pieces )
Example:
<?php
$myArray = ['one','two','three'];
echo implode(',', $myArray);
// one,two,three
echo implode(' Mississippi;', $myArray);
// one Mississippi; two Mississippi; three Mississippi;
Foreach
foreach: The foreach construct provides an easy way to iterate over arrays, objects or traversables.
foreach (array_expression as $key => $value)
...statement...
Example:
<?php
$myArray = ['one','two','three'];
$output = '';
foreach ($myArray as $val) {
$output .= $val . ',';
}
echo $output;
// one,two,three,
Notice that on this version we have an extra comma to deal with
<?php
echo rtrim($output, ',');
// one,two,three
List
list: Assign variables as if they were an array
array list ( mixed $var1 [, mixed $... ] )
Example:
<?php
$myArray = ['one','two','three'];
list($one, $two, $three) = $myArray;
echo "{$one}, {$two}, {$three}";
// one, two, three
Note that on this version you have to know how many values you want to deal with.
Array Reduce
array_reduce: Iteratively reduce the array to a single value using a callback function
mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
Example:
<?php
$myArray = ['one', 'two', 'three'];
echo array_reduce($myArray, function ($carry, $item) {
return $carry .= $item . ', ';
}, '');
// one, two, three,
This method also causes an extra comma to appear.
While
while: while loops are the simplest type of loop in PHP.
while (expr)
...statement...
Example:
<?php
$myArray = ['one', 'two', 'three'];
$output = '';
while (!empty($myArray)) {
$output .= array_shift($myArray);
$output .= count($myArray) > 0 ? ', ' : '';
}
echo $output;
// one, two, three
Notice that we've handled the erroneous comma in the loop. This method is destructive as we alter the original array.
Sprintf and String Repeat
sprintf: My best attempt of actually using the str_repeat function:
<?php
$myArray = ['one','two','three'];
echo rtrim(sprintf(str_repeat('%s, ', count($myArray)), ...$myArray), ', ');
// one, two, three
Notice that this uses the splat operator ... to unpack the array as arguments for the sprintf function.
Obviously a lot of these examples are not the best or the fastest but it's good to think out of the box sometimes.
There's probably many more ways and I can actually think of more; using array iterators like array_walk, array_map, iterator_apply and call_user_func_array using a referenced variable.
If you can think of any more post a comment below :-)

What is the best/fastest way to echo duplicate array values and their count in php

I need your advice if there is a better (and faster) way to output duplicate array values and their count in php.
Currently, I am doing it with the below code:
The initial input is always a text string like this:
$text = "a,b,c,d,,,e,a,b,c,d,f,g,"; //Note the comma at the end
Then I get the unique array values:
$arrText = array_unique(explode(',',rtrim($text,',')));
Then I count the duplicate values in the array (excluding the empty ones):
$cntText = array_count_values(array_filter(explode(',', $text)));
And finally I echo the array values and their count with a loop inside a loop:
foreach($arrText as $text){
echo $text;
foreach($cntText as $cnt_text=>$count){
if($cnt_text == $text){
echo " (".$count.")";
}
}
I am wondering if there is a better way to output the unique values and their count without using a loop inside a loop.
Currently I have chosen this approach because:
My input is always a text string
The text string contains empty values and has a comma at the end
I need to echo only non empty values
Let me know your expert advices!
You can write your code to print the values a lot shorter (Also I wrote other things a bit shorter):
You don't need rtrim() or array_unique(), you only need explode() and with array_filter() you take care of the empty values. Then just use array_count_values() and loop through the values.
<?php
$text = "a,b,c,d,,,e,a,b,c,d,f,g,";
$filtered = array_filter(explode(",", $text));
$countes = array_count_values($filtered);
foreach($countes as $k => $v)
echo "$k ($v)";
?>
output:
a (2)b (2)c (2)d (2)e (1)f (1)g (1)
You shouldn't need to make two arrays as array_count_values keys are the value of the text.
$myArray = array_count_values(array_filter(explode(',',$text)));
foreach($myArray as $key => $value){
echo $key . ' (' . $value . ')';
}

php array_sum returning first value only

I'm fairly new at php, but this seems to be me overlooking something completely basic?
I have some values in a database column, that are comma separated like so:
1,2,3
When I try to get the sum of the values, I expect the echo of array_sum to be 6, but I only get returned the first value ie. "1"
echo $amount; //Gives 1,2,3 etc.
$amount_array = array($amount);
echo array_sum($amount_array); //Only prints "1"
print_r($amount); // shows 1,2,3
print_r($amount_array); // shows Array ( [0] => 1,2,3 )
It's a string not an array, you have to split it using explode function:
$exploded = explode ( "," , $amount_array);
var_dump($exploded);
To use the array_sum the string needs to be converted to an array
You need to use the explode function:
$amount_array = explode(',', $amount);
So you total code should be like this:
$amount_array = explode(',', $amount);
echo array_sum($amount_array);
array_sum() works by adding up the values in an array. You only have one key=>value pair in your array: key 0 with a value of 1,2,3.
If you have a comma-separated list, and want that to be an array, I would use the explode() function to turn the list into the proper key=>value pairs that array_sum() would expect.
Try
$amount_array = explode(',',$amount);
You can not initialize an array the way you intend. You are passing in a comma-separated string, which is just a single argument. PHP doesn't automagically convert that string into separate arguments for you.
In order to convert a comma-separated string into an array of individual values you can break up the string with a function like explode(), which takes a delimiter and a string as its arguments, and returns an array of the delimiter-separated values.
$amount_array = explode( ',', $amount ); // now $amount_array is the array you intended

Get array number from Array with String value

I have an array with string value in PHP for example : arr['apple'], arr['banana'], and many more -about 20-30 data (get it from some process). Now I want to get its value and return it to one variable.
For example, I have Original array is like this:
$arr['Apple']
$arr['Banana']
and more..
and result that I want is like this:
$arr[0] = "Apple"
$arr[1] = "Banana"
and more..
Any idea how to do that?
Why not using array_keys()?
$new_array = array_keys($array);
Use array_flip()
$new_arr = array_flip($old_arr);
Demonstration
use foreach loop
foreach($arr as $key => $val){
$new_var[] = $key;
}
use array_keys function:
$keys = array_keys($arr);
It returns an array of all the keys in array.

call_user_func_array + array_intersect with an array of array names, possible?

Sorry for the confusing title...
I need to perform an array_intersect() against a variable number of arrays. To do this it seems I need to use the call_user_func_array() function, however, this doesn't seem to be working and gives me the error:
Warning: array_intersect() [function.array-intersect]: Argument #1 is not an array in...
But, if I "print_r" the array to make sure then I see that it is an array:
Array ( [0] => arr_0 [1] => arr_1 )
My code (trimmed to just show the broken part):
$i = 0;
$arr_results = array();
foreach($arr_words as $word) {
$arrayname = "arr_".$i;
$$arrayname = array();
while ($row = mysql_fetch_assoc($search)) {
array_push($$arrayname, $row['id']);
}
array_push($arr_results, "$arrayname");
$i++
}
$matches = call_user_func_array('array_intersect',$arr_results);
In the full code I'm populating the arrays in the foreach loop with data obtained from sql queries.
From my comments:
"$arrayname" is a string, not an array. call_user_func_array will pass each element in $arr_results as argument to array_intersect. array_intersect expects arrays as arguments, but each item in $arr_results is a string, not an array.
All you have to do is create an array of arrays instead of array names:
$arr_results = array();
foreach($arr_words as $word) {
$ids = array();
while ($row = mysql_fetch_assoc($search)) {
$ids[] = $row['id'];
}
$arr_results[] = $ids;
}
$matches = call_user_func_array('array_intersect',$arr_results);
I turn $arrayname into an array with $$arrayname = array();
Right, you create a variable, lets say arr_0 which will point to array. But there is still a difference between the variable name arr_0 and the string containing the variable name "arr_0". You create an array of strings, and that just won't work. PHP does not know that the string contains a name of a variable. For example, consider this:
$arr = "arr_0";
echo $arr[0];
Based on your logic, it should output the first element of the array, but it does not, because $arr is a string, not an array, although it contains the name of a variable.
You'd have to use eval, but you really should not. You could also use variable variables again:
array_push($arr_results, $$arrayname);
that would work as well, but as I said, variable variables are confusing and in 99% of the cases, you are better of with an array.

Categories