PHP - Counting matching arrays in array - php

I have an array structure that looks like this:
Array
(
[0] => Array
(
[type] => image
[data] => Array
(
[id] => 1
[alias] => test
[caption] => no caption
[width] => 200
[height] => 200
)
)
[1] => Array
(
[type] => image
[data] => Array
(
[id] => 2
[alias] => test2
[caption] => hello there
[width] => 150
[height] => 150
)
)
)
My question is, how can I get a count of the number of embedded arrays that have their type set as image (or anything else for that matter)? In practise this value can vary.
So, the above array would give me an answer of 2.
Thanks

The simplest way would simply be to loop over all the child arrays and check their type, incrementing a counter if it matches the required type.
$count = 0;
foreach ( $myarray as $child ){
if ( $child['type'] == 'image' ){
$count++;
}
}
If you have PHP 5.3.0 or better you could use array_reduce (untested):
$count = array_reduce($myarray,
function($c, $a){ return $c + (int)($a['type'] == 'image'); },
0
);
Both of these could be moved into a function returning $count which would allow you to specify the type to count. For example:
function countTypes(array $haystack, $type){
$count = 0;
foreach ( $haystack as $child ){
if ( $child['type'] == $type ){
$count++;
}
}
return $count;
}
As you can see from other answers there is far more error checking you could do, however you as you haven't said what should be impossible (which you would want to use assert for).
The possible errors are:
The child is not an array
The child does have the type key set
If your array should always be set out like your example, failing silently (by putting a check in an if statement) would be a bad idea as it would mask an error in the program elsewhere.

You'll have to iterate over each element of your array and check whether element match your condition:
$data = array(...);
$count = 0;
foreach ($data as $item) {
if ('image' === $item['type']) {
$count++;
}
}
var_dump($count);

<?php
$arr = // as above
$result = array();
for ( $i = 0; $i < count( $arr ); $i++ )
{
if ( !isset( $result[ $arr[$i]['type'] ] ) )
$result[ $arr[$i]['type'] ] = 0;
$result[ $arr[$i]['type'] ]++;
}
echo $result['image']; // 2
?>

In addition to Yacoby's answer, you could do it functional-style with a closure if you're using PHP 5.3:
$count = 0;
array_walk($array, function($item)
{
if ($item['type'] == 'image')
{
$count++;
}
});

Try this:
function countArray(array $arr, $arg, $filterValue)
{
$count = 0;
foreach ($arr as $elem)
{
if (is_array($elem) &&
isset($elem[$arg]) &&
$elem[$arg] == $filterValue)
$count++;
}
return $count;
}
For your example, you would call it like this:
$result = countArray($array, 'type', 'image');

Related

Count() into a multidimensional array in PHP

If I have this array:
Array (
[0] => Array (
[booking_id] => 1
[booking_status] => confirmed
[client_name] => Bale
[client_firstname] => Gareth
[days] => Array (
[day_id] => 2016-11-23,2016-11-24
[room_id] => 2
)
)
)
How can I get the number of item into day_id please?
You can use array_reduce to iterate through array items and get a final result. Take a look at this:
function reduce_func($carry, $item){
if (isset($item['days']) && !empty($item['days']['day_id'])){
$carry += count(array_unique(array_filter(explode(',', $item['days']['day_id']))));
}
return $carry;
}
$result = array_reduce($arr, "reduce_func", 0);
Update
note that you can also provide a callback to the array_filter to filter out your desired entries to be counted, eg. regex checking each entry to be a valid date. Here's PHP manual for array_filter.
$sum = 0;
foreach ($data as $booking) {
$sum += sizeof(explode(",",$booking["days"]["day_id"]));
}
$sum =0;
for ($count = 0; $count < count($data); $count++) {
$booking = $data[$count];
$day_ids = explode(",", $booking['days']['day_id'];
$sum = $sum + count($day_ids);
}

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

Sort array by key value

So I have this array.
Array
(
[0] => Array
(
[key_1] => something
[type] => first_type
)
[1] => Array
(
[key_1] => something_else
[type] => first_type
)
[2] => Array
(
[key_1] => something_else_3
[type] => second_type
)
[3] => Array
(
[key_1] => something_else_4
[type] => second_type
)
)
I have to sort by type value in a pattern like this:
first_type
second_type
first_type
second_type
My questions is, how can I do this?
Thanks a lot!
You need to use usort with a custom comparison function that compares the key_1 sub-keys of each item (you can use strcmp to do this conveniently). Assuming you do not want to change the structure of the resulting array, it would look something like this:
$arr = /* your array */
usort($arr, function($a, $b) { return strcmp($a['key_1'], $b['key_1']); });
So here's how I got it to work:
function filter_by_value($array, $index, $value) {
if(is_array($array) && count($array) > 0) {
foreach(array_keys($array) as $key){
$temp[$key] = $array[$key][$index];
if ($temp[$key] == $value){
$newarray[$key] = $array[$key];
}
}
}
return $newarray;
}
$array = /* array here */
$type1 = array_values(filter_by_value($array, 'type', '1'));
$type2 = array_values(filter_by_value($array, 'type', '2'));
$i = 1; $x = 1; $y = 1;
$sorted = array();
foreach ($array as $a) {
if ($i % 2) {
$sorted[$i-1] = $type1[$x-1];
$x++;
} else {
$sorted[$i-1] = $type2[$y-1];
$y++;
}
$i++;
}
Found filter_by_value() on php.net but I don't remember where so, that's not made by me.
Maybe this is not the best solution but it works pretty fine.
If sort() and its relevant alternatives don't work you will have to use usort() or uasort() with a custom function to sort this array.

How can i count the two-dimesional array - PHP

Array
(
[0] => Array
(
[not_valid_user] => Array
(
[] => asdsad
)
)
[1] => Array
(
)
[2] => Array
(
[not_valid_user] => Array
(
[] => asdasd
)
)
)
I need the count of array [not_valid_user]
For example:
The above arrays count is 2. How can i get it?
Thanks in advance...
$invalidUsersFound = 0;
foreach ( $data as $k => $v ) {
if ( IsSet ( $v['not_valid_user'] ) === true )
$invalidUsersFound++;
}
This should do the trick.
If what you want is count of all elements in every "not_valid_user" array,
$count=0;
foreach($mainArray as $innerArray)
{
if (isset($innerArray['not_valid_user']) && is_array($innerArray['not_valid_user']))
{
$count += count($innerArray['not_valid_user']);// get the size of the 'not_valid_user' array
}
}
echo $count;//Count of all elements of not_valid_user
<?php
$count=0;
foreach($mainArray as $innerArray)
{
if(isset($innerArray['not_valid_user']))
$count++;
}
echo $count;//Count of not_valid_user
?>
$cnt = 0;
array_map(function ($value) use (&$cnt) {
$cnt += (int)(isset($value["not_a_valid_user"]));
}, $arr);
echo $cnt;
Providing your version of PHP supports anonymous functions.

PHP - how to compare value of arrays in dynamic way?

Ok, I have following 'challange';
I have array like this:
Array
(
[0] => Array
(
[id] => 9
[status] => 0
)
[1] => Array
(
[id] => 10
[status] => 1
)
[2] => Array
(
[id] => 11
[status] => 0
)
)
What I need to do is to check if they all have same [status].
The problem is, that I can have 2 or more (dynamic) arrays inside.
How can I loop / search through them?
array_diff does support multiple arrays to compare, but how to do it? :(
Which ever loop I have tried, or my Apache / browser died - or I got completely bogus data back.
You could just put the problem apart to make it easier to solve.
First get all status items from your array:
$status = array();
forach($array as $value)
{
$status[] = $value['status'];
}
You now have an array called $status you can see if it consists of the same value always, or if it has multiple values:
$count = array_count_values($status);
echo count($count); # number of different item values.
Try this code:
$status1 = $yourArray[0]['status'];
$count = count($yourArray);
$ok = true;
for ($i=1; $i<$count; $i++)
{
if ($yourArray[$i]['status'] !== $status1)
{
$ok = false;
break;
}
}
var_dump($ok);
function allTheSameStatus( $data )
{
$prefStatus = null;
foreach( $data as $array )
{
if( $prefStatus === null )
{
$prefStatus = $array[ 'status' ];
continue;
}
if( $prefStatus != $array[ 'status' ] )
{
return false;
}
}
return true;
}
I'm not sure what you want as output but you could iterate through the outer array and create an output array that groups the inner arrays by status:
$outputArray = array();
foreach ($outerArray as $an_array) {
$outputArray[$an_array['status']][] = $an_array['id'];
}

Categories