PHP - Best way to count the number of things in array - php

I'm running a foreach loop on an array of students, that have a key ['all_user_grades']. What is the best way to count the number of As,Bs,Cs,Ds,Es and fails for each student in the array.
Here's what my array looks like:
[11] => Array
(
[id] => 10
[All_User_Grades] => A, A, D, A, E
)
Here's what my foreach looks like so far:
foreach($user_grades as $k => $v){
$aug = $v['All_User_Grades'];
$all_user_grades_arr = explode(',', $aug);
}

You can use the array_count_values() function:
$array = array('A', 'A', 'D', 'A', 'E');
$result = array_count_values($array);
print_r($result);
It outputs:
Array
(
[A] => 3
[D] => 1
[E] => 1
)

You can use substr_count() for this like so
$As = substr_count($aug, 'A');
$Bs = substr_count($aug, 'B');
//etc
or, just like you already did, explode and use the array for calculation
$all_user_grades_arr = explode(',', $aug);
$grades = array('A' => 0, 'B' => 0', ...);
foreach ($all_user_grades_arr as $val) {
$grades[ trim($val) ]++;
}
The trim() here is necessary to get rid of unnecessary whitespaces

You can try this way using array_count_values, i have used for single array, you change as per your requirements. See Demo http://ideone.com/YrGfPD
//PHP
$v=array('Id'=>10,'All_User_Grades'=>'A,A,D,A,E');
$aug = $v['All_User_Grades'];
$all_user_grades_arr = explode(',', $aug);
echo '<pre>';
print_r(array_count_values($all_user_grades_arr));
echo '</pre>';
//OUTPUT
Success time: 0.02 memory: 24448 signal:0
Array
(
[A] => 3
[D] => 1
[E] => 1
)

Related

Basic Array Referencing Php

How can I reference the following dynamic arrays' elements ?
$log = array();
$arr1 = array ('a'=>'6:16pm','b'=>2,'c'=>3,'d'=>4,'e'=>5);
$arr2 = array ('a'=>'6:24pm','b'=>20,'c'=>30,'d'=>40,'e'=>50);
$log = array_merge($log, array($arr1['a']=>$arr1));
$log = array_merge($log, array($arr2['a']=>$arr2)); //<-- to use time as key
print_r($log);
for ($x = 0; $x < count($log); $x++) {
print_r ($log[0][$x]['a']); // <-- referencing issue Undefined offset: 0 .. line 20
}
//------ produces
Array
(
[6:16pm] => Array
(
[a] => 6:16pm
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
[6:24pm] => Array
(
[a] => 6:24pm
[b] => 20
[c] => 30
[d] => 40
[e] => 50
)
)
I'm pretty sure it has something to do with the way I'm naming the $log main array.. and there's probably a better way to do what I wish(.. add/ new elements to $log using the time key) - Still a php noob unfortunately. Thanks for any pointers.
It's a little unclear, but just create an array from the two and use the a index:
$log = array($arr1, $arr2);
foreach($log as $values) {
echo $values['a']; // 6:16pm
}
Or if you want the time as the index, then re-index on a:
$log = array($arr1, $arr2);
$log = array_column($log, null, 'a');
foreach($log as $time => $values) {
echo $time; // 6:16pm
echo $values['b']; // 2
}
It's prettier, but there is no need for the time as the index unless you are going to use ksort or access by index:
echo $log['6:16pm']['b'];
in cases that you don't know your key is recommended that you use foreach statement:
$logs = array();
$arr1 = array ('a'=>'6:16pm','b'=>2,'c'=>3,'d'=>4,'e'=>5);
$arr2 = array ('a'=>'6:24pm','b'=>20,'c'=>30,'d'=>40,'e'=>50);
$logs = array_merge($logs, array($arr1['a']=>$arr1));
$logs = array_merge($logs, array($arr2['a']=>$arr2)); //<-- to use time as key
$logs = array();
$arr1 = array('a' => '6:16pm', 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$arr2 = array('a' => '6:24pm', 'b' => 20, 'c' => 30, 'd' => 40, 'e' => 50);
$logs = array_merge($logs, array($arr1['a'] => $arr1));
$logs = array_merge($logs, array($arr2['a'] => $arr2)); //<-- to use time as key
foreach ($logs as $time => $log) {
//index:
print_r($time);
//array:
print_r($log);
// a array key:
print_r($log['a']);
//go through all keys:
foreach ($log as $letter => $value) {
//index:
print_r($letter);
//value: a
print_r($value);
}
}
You can not call array like
print_r ($log[0]);
Because your array has key. which is 6:16pm for first one and 6:24pm for second. you have to call it by key name you have assigned. your array should be called like this in everywhere even in loop
print_r ($log["6:16pm"]);

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,
)

Merge array values in a `foreach` loop [duplicate]

This question already has answers here:
PHP append one array to another (not array_push or +)
(11 answers)
Closed last month.
I have two arrays that are inside foreach loop, I want to merge them to one key and value.
let the first array "array1" inside foreach:
$array1 = ['x', 'y', 'z'];
let the second array "array2" inside foreach:
$array2 = ['a', 'b', 'c'];
Expected output should be as follows:
$mergeArray = [0=>['x', 'y', 'z','a', 'b', 'c']];
What I have done is the following:
$mergeArray = [];
foreach ($customer as $key => $value) {
$mergeArray[] = $value['items1'];
$mergeArray[] = $value['items2'];
echo '<pre>';
print_r($mergeArray);
exit;
}
Thanks and welcome all suggestions
Use array_merge:
$mergeArray[] = array_merge($value['item1'], $value['item2']);
Also, the exit should not be in the loop, that will prevent the loop from repeating.
You can do it with this code
$mergeArray = [];
foreach ($customer as $key => $value) {
$mergeArray[0] =array_merge ( $value['items1'], $value['items2']);
echo '<pre>';
print_r($mergeArray);
exit;
}
Why use a foreach loop at all? Am I missing something?
$array1 = array('x', 'y', 'z');
$array2 = array('a', 'b', 'c');
$mergeArray[0] = array_merge($array1, $array2);
Output:
Array
(
[0] => Array
(
[0] => x
[1] => y
[2] => z
[3] => a
[4] => b
[5] => c
)
)

Get last key-value pair in PHP array

I have an array that is structured like this:
[33] => Array
(
[time] => 1285571561
[user] => test0
)
[34] => Array
(
[time] => 1285571659
[user] => test1
)
[35] => Array
(
[time] => 1285571682
[user] => test2
)
How can I get the last value in the array, but maintaining the index [35]?
The outcome that I am looking for is this:
[35] => Array
(
[time] => 1285571682
[user] => test2
)
try to use
end($array);
$last = array_slice($array, -1, 1, true);
See http://php.net/array_slice for details on what the arguments mean.
P.S. Unlike the other answers, this one actually does what you want. :-)
You can use end to advance the internal pointer to the end or array_slice to get an array only containing the last element:
$last = end($arr);
$last = current(array_slice($arr, -1));
If you have an array
$last_element = array_pop(array);
Example 1:
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
print_r(end($arr));
Output = e
Example 2:
ARRAY without key(s)
$arr = array("a", "b", "c", "d", "e");
print_r(array_slice($arr, -1, 1, true));
// output is = array( [4] => e )
Example 3:
ARRAY with key(s)
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
print_r(array_slice($arr, -1, 1, true));
// output is = array ( [lastkey] => e )
Example 4:
If your array keys like : [0] [1] [2] [3] [4] ... etc. You can use this:
$arr = array("a","b","c","d","e");
$lastindex = count($arr)-1;
print_r($lastindex);
Output = 4
Example 5:
But if you are not sure!
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
$ar_k = array_keys($arr);
$lastindex = $ar_k [ count($ar_k) - 1 ];
print_r($lastindex);
Output = lastkey
Resources:
https://php.net/array_slice
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/function.count.php
https://www.php.net/manual/en/function.end.php
Like said Gumbo,
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
Another solution cold be:
$value = $arr[count($arr) - 1];
The above will count the amount of array values, substract 1 and then return the value.
Note: This can only be used if your array keys are numeric.
As the key is needed, the accepted solution doesn't work.
This:
end($array);
return array(key($array) => array_pop($array));
will return exactly as the example in the question.
"SPL-way":
$splArray = SplFixedArray::fromArray($array);
$last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);
Read more about SplFixedArray and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array here => The SplFixedArray class.

How to remove values from an array whilst renumbering numeric keys

I have an array which may contain numeric or associative keys, or both:
$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
[0] => a
[1] => b
[2] => c
[foo] => bar
[3] => d
[4] => e
)*/
I want to be able to remove an item from the array, renumbering the non-associative keys to keep them sequential:
$x = remove($x, "c");
print_r($x);
/* desired output:
(
[0] => a
[1] => b
[foo] => bar
[2] => d
[3] => e
)*/
Finding the right element to remove is no issue, it's the keys that are the problem. unset doesn't renumber the keys, and array_splice works on an offset, rather than a key (ie: take $x from the first example, array_splice($x, 3, 1) would remove the "bar" element rather than the "d" element).
This should re-index the array while preserving string keys:
$x = array_merge($x);
You can fixet with next ELEGANT solution:
For example:
<?php
$array = array (
1 => 'A',
2 => 'B',
3 => 'C'
);
unset($array[2]);
/* $array is now:
Array (
1 => 'A',
3 => 'C'
);
As you can see, the index '2' is missing from the array.
*/
// SOLUTION:
$array = array_values($array);
/* $array is now:
Array (
0 => 'A',
1 => 'C'
);
As you can see, the index begins from zero.
*/
?>
I've come up with this - though I'm not sure if it's the best:
// given: $arr is the array
// $item is the item to remove
$key = array_search($item, $arr); // the key we need to remove
$arrKeys = array_keys($arr);
$keyPos = array_search($key, $arrKeys); // the offset of the item in the array
unset($arr[$key]);
array_splice($arrKeys, $keyPos, 1);
for ($i = $keyPos; $i < count($arrKeys); ++$i) {
if (is_int($arrKeys[$i])) --$arrKeys[$i]; // shift numeric keys back one
}
$arr = array_combine($arrKeys, $arr); // recombine the keys and values.
There's a few things I've left out, just for the sake of brevity. For example, you'd check if the array is associative, and also if the key you're removing is a string or not before using the above code.
Try array_diff() it may not order the new array correctly though
if not the following should work
You will need to iterate over it in the remove function.
function remove($x,$r){
$c = 0;
$a = array();
foreach ($x as $k=>$v){
if ($v != $r) {
if (is_int($k)) {
$a[$c] = $v;
$c++;
}
else {
$a[$k] = $v;
}
}
}
return $a;
}
DC
I don't think there is an elegant solution to this problem, you probably need to loop to the array and reorder the keys by yourself.

Categories