How can i count the two-dimesional array - PHP - 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.

Related

PHP Unique MultiDimensional Array Issue

So, I am getting unique values from my MD array utilizing the following function:
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach( $array as $val ) {
if ( ! in_array( $val[$key], $key_array ) ) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
My array is similar to the following:
Array (
[0] =>
Array (
'name' => 'Nevada'
)
[1] =>
Array (
'name' => 'Colorado'
)
[2] =>
Array (
'name' => 'Nevada'
)
[3] =>
Array (
'name' => 'Colorado'
)
[4] =>
Array (
'name' => 'Oklahoma'
)
[5] =>
Array (
'name' => 'Nevada'
)
[6] =>
Array (
'name' => 'Nevada'
)
)
And using the function (unique_multidim_array ( $term_arr, 'name' )) above I am getting a single Nevada and a single Colorado, however, it is not returning Oklahoma
What can I do to ensure that it will return unique values, even if there are no duplicates?
Your resulting array keeps the original indices, and, depending on how you are iterating over it, you might get unexpected results. Try resetting the indices:
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach( $array as $val ) {
if ( ! in_array( $val[$key], $key_array ) ) {
$key_array[$i] = $val[$key];
$temp_array[] = $val; // <--- remove the $i
}
$i++;
}
return $temp_array;
}
Or, as you say, array_values() will help too:
$term_arr = array_values ( unique_multidim_array ( $term_arr, 'name' ) );
PHP already has a function to remove duplicates from an array
array_unique(array)
should do the trick

How to Print associative array in foreach

I have an associative array in php, how can i print it with php foreach loop
Array( [0] => Array ( [fb_user_id] => 100000058716604 [accept_status] => 1 ) [1] => Array ( [fb_user_id] => 100004069844270 [accept_status] => 1 ) )
Tried this but no success, i want to print the fb_user_id
foreach($resulttotal[fb_user_id] as $value)
{
echo $value;
}
Please help me, Thanks
You doing incorrectly, It will be like:
foreach($resulttotal as $value)
{
echo $value['fb_user_id'];
}
It would make more sense to use a regular for loop.
for($i = 0; $i < count($resulttotal); $i++) {
$row = & $resulttotal[$i];
echo $row['fb_user_id'];
}
But this could be a foreach too.
foreach($resulttoal as $key) {
echo $key['fb_user_id']
}

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.

help needed restructuring a php array

I was wondering if anyone could help me restructure a predefined php array. The output of my current array is:
Array
(
[71-ctns] => 1
[71-units] => 1
[308-units] => 1
[305-ctns] => 1
[306-units] => 2
)
And I would like it to look like:
Array
(
[71] => Array
(
[ctns] => 1
[units] => 1
)
[308] => Array
(
[units] => 1
)
[305] => Array
(
[ctns] => 1
)
[306] => Array
(
[units] => 2
)
)
Is this possible?
This should do it
$merged = array();
foreach($a as $k=>$v){
$t = explode('-',$k);
$id = intval($t[0]);
if(!array_key_exists($id, $merged))
$merged[$id] = array();
$merged[$id][$t[1]] = $v;
}
EDIT:
Sorry you should use explode instead of split.
Yes, but you need to loop (note: array_map can also work, but this example is more explicit):
$fin = array();
foreach( $complex as $item => $val )
{
$pieces = explode('-', $item);
$fin[$pieces[0]] = isset($fin[$pieces[0]])?:array();
$fin[$pieces[0]][$pieces[1]] = $val;
}
Find below code to restructure a predefined php array
<?php
$newArray=array();
$result = array("71-ctns"=>1,"71-units"=>1,"308-ctns"=>1,"308-units"=>1,"305-units"=>1,"306-units"=>2);
if(is_array($result) && count($result)>0) {
foreach($result as $key=>$val) {
$getKeyArray = explode("-",$key);
$newArray[$getKeyArray[0]][$getKeyArray[1]] =$val;
}
}
print"<pre>";
print_r($newArray);
?>

PHP - Counting matching arrays in array

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');

Categories