How to count the inner array count too - php

I have an array like as
$arr[0] = 'summary';
$arr[1]['contact'][] = 'address1';
$arr[1]['contact'][] = 'address2';
$arr[1]['contact'][] = 'country';
$arr[1]['contact'][] = 'city';
$arr[1]['contact'][] = 'pincode';
$arr[1]['contact'][] = 'phone_no';
$arr[2]['work'][] = 'address1';
$arr[2]['work'][] = 'address2';
$arr[2]['work'][] = 'country';
$arr[2]['work'][] = 'city';
$arr[2]['work'][] = 'pincode';
$arr[2]['work'][] = 'phone_no';
Using count($arr) it returns 3 but I also need to count inner array values so it will return 13
What I've tried so far is
function getCount($arr,$count = 0) {
foreach ($arr as $value) {
if (is_array($value)) {
echo $count;
getCount($value,$count);
}
$count = $count+1;
}
return $count;
}
echo getCount($arr);
But its not working as expected

You can use array_walk_recursive for this. This may help -
$tot = 0;
array_walk_recursive($arr, function($x) use(&$tot) {
$tot++;
});
But It is a recursive function so you need to be careful about that.
In that getCount() method you are not storing the count of the array anywhere. So for every call $count is incremented by 1 only.
DEMO

Simply try this
function getCount($arr, $count = 0) {
foreach ($arr as $value) {
if (is_array($value)) {
$count = getCount($value, $count);
} else {
$count = $count + 1;
}
}
return $count;
}
echo getCount($arr);
What you were doing over here is that you were not storing the value within any variable and that is making an issues with your code as you were on the perfect way

If you need to count only the first two levels, you can do a simple foreach, no need to use a recursive function!:
$count = 0;
foreach( $bigArray as $smallArray ){
if( is_array( $smallArray ) )
$count += count( $smallArray );
else
$count ++;
}

Perhaps I am naive in my approach, but I simply use the sizeof() function. The function's documentation shows that it can take a second argument 1 to tell the function to recursively count multidimensional arrays.
So, to get the 'count' you could simply write sizeof($arr, 1); and it should return 13.
I recognize the value of writing your own function, but doesn't this built-in PHP method solve the problem quite succinctly?

Related

php array sorting with next value difference

can anyone help me with this following Array sorting
Input
$array=array(1,2,3,6,7,8,100,101,200);
Output:
$new_array=array(
0=>array(1,2,3),
1=>array(6,7,8),
2=>array(100,101),
3=>array(200)
);
Thanks in advance!
$array=array(1,2,3,6,7,8,100,101,200);
$new_array = array();
$lastNumber = '';
foreach($array as $number) {
if($lastNumber === '') {
$otherArray = array($number);
}
elseif($lastNumber + 1 !== $number) {
$new_array[] = $otherArray;
$otherArray = array($number);
}
else{
$otherArray[] = $number;
}
$lastNumber = $number;
}
$new_array[] = $otherArray;
print_r($new_array);
You can loop over the array and check the distance to the next element in the array. If this distance is larger then one add a new sub array:
$array=array(1,2,3,6,7,8,100,101,200);
$result=array(array());
for($i=0; $i<count($array)-1; $i++)
{
if($array[$i+1]-$array[$i]==1)
{
// If difference to next number is one -> push
array_push($result[count($result)-1], $array[$i]);
}
else
{
// ... else: Push and create new array for the next element
array_push($result[count($result)-1], $array[$i]);
array_push($result, array());
}
}
// Push the last number
array_push($result[count($result)-1], $array[$i]);
print_r($result);
Just a different approach with array_push()...
Pretty simple: loop through the numbers, remember the last one, if the current number is not the successor of the last one, add a new array to your result, push into the last array in your result.
$result = [];
$last = null;
foreach ($array as $number) {
if ($last !== $number - 1) {
$result[] = [];
}
$result[count($result) - 1][] = $number;
$last = $number;
}
You could even get rid of $last and directly read the last array element of the last array element of $result, but that would make the code actually more complicated.

concatenate arrays with associative keys

I'll let the code speak:
$params = array();
$qtyCount = count(array(1,2,3,4,5));
$qtyAr = array(6,7,8,9,10);
$i = 1;
while($i <= $qtyCount){
$params['quantity_'.$i] .= $qtyAr[$i];
$i++;
}
But when I do this, the last value is missing.
BTW: the values in the qtyCount and qtyAr are bugus... just for example.
I would opt for a simpler approach:
array_walk($qtyAr, function($item, $index) use (&$params) {
$key = sprintf("quantity_%u", $index);
$params[$key] = $item;
});
It appears that you are starting at the wrong index (1), $i should be = 0 as others have pointed out.
You're missing the last element because your unasssociated array starts with 0 and your loop starts with 1. This is why foreach works so much better because it iterates over ALL your elements.
$qtyAr = array(6,7,8,9,10);
$i = 1;
foreach($qtyAr as $val) {
$params['quantity_' . $i] = $val;
$i++;
}

Counting the number of dimensions in an array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to find how how “deep” a PHP array is?
I am trying to write a method to count the number of dimensions of an array. The following gives me a correct count of dimensions
$array = array();
$array[0] = array();
$array[0][0] = 0;
$array[0][1] = array();
$array[0][1][0] = 10;
$array[0][1][1] = 11;
echo '<p>'.\utility\arrayTools\arrayTools::numberOfDimensions($array).'</p>';
//3 Dimensons
The second examples also gives me a correct count of the number of dimensions
$array = array();
$array[0] = array();
$array[0][0] = 0;
$array[0][1] = array();
$array[0][1][0] = 10;
$array[0][1][1] = 11;
$array[1] = 1;
$array[2] = 2;
//3 Dimensions
But the following example gives me too high of a count
$array = array();
$array[0] = array();
$array[0][0] = 0;
$array[0][1] = array();
$array[0][1][0] = 10;
$array[0][1][1] = 11;
$array[1] = 1;
$array[2] = 2;
$array[3] = array();
$array[3][0] = 30;
//Should still be 3 dimensions, but gives me 4
The method I am using is below
//Method
public static function numberOfDimensions($array)
{
if(func_num_args() === 2){
if(is_int(func_get_arg(1))){
$number_of_dimensions = func_get_arg(1);
}else{
throw new Exception('The second argumment must be an interger');
}
}else{
$number_of_dimensions = 0;
}
if(is_array($array) === TRUE){
$number_of_dimensions++;
if(self::isMultiDimensional($array) === TRUE){
foreach($array as $iteration){
$number_of_dimensions = self::numberOfDimensions($iteration,$number_of_dimensions);
}
return $number_of_dimensions;
}else{
return $number_of_dimensions;
}
}else{
return $number_of_dimensions;
}
}
I already know the problem is it is still adding for every multidimensional even though the count may be equal to or less then the number of dimensions. But what I can't figure out is how to get it to find the highest number of dimensions and stop counting
Here is a simpler version of your script
function numberOfDimensions($array) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$d = 0;
foreach ( $it as $v )
$it->getDepth() >= $d and $d = $it->getDepth();
return ++ $d;
}
From another answer here on SO:
function array_depth($array) {
$max_depth = 1;
foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}
I havn't written any PHP in a very long while, so there may very well be mistakes in my code, excuse me in advance.
function numberOfDimensions($array,$so_far=0){
if !is_array($array){
return 0;
}
$max_dims = 0;
foreach($array as $element){
$element_dims = numberOfDimensions($array);
$max_dims = max($max_dims,$element_dims);
}
return $max_dims +1;
}
This function assumes it is being called with an array as parameter, thus the minimum depths is 1.
It then recursively looks at all child elements, and if the child is deeper than already known, it add the depth of the child to the calculated depth:
function numberOfDimensions($subject) {
// scalar value has depth 0
if(!is_array($subject)) return 0;
// array has min depth of 1
$depth = 1;
foreach ($subject as $element) {
if (is_array($element)) {
// is the sub array deeper than already known?
$sub_depth = numberOfDimensions($element);
if ($sub_depth >= $depth) {
$depth += $sub_depth;
}
}
}
return $depth;
}

php or any program language

Hi anybody can help me to find the maximum value of the array that are given in the below . i expect the result of 650 is the maximum value....
$my_array = array(array(128,300,140)10,15,array(130,array(500,650)));
Here you go, using RecursiveArrayIterator in 3 readable lines of code:
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flattenedArray = iterator_to_array($it);
$max = max($flattenedArray);
Or, if you want to not flatten (and copy), but prefer to iterate (uses far less memory, but slower):
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$max = 0;
foreach ($it as $value) {
$max = max($value, $max);
}
Flatten the array, then call max() on it. The return value of max() should be 650 from your example.
Also possible is
$data = array(array(128,300,140),10,15,array(130,array(500,650)));
$max = 0;
array_walk_recursive(
$data,
function($val) use (&$max) {
if($val > $max) $max = $val;
}
);
echo $max; // 650
You could also do it recursively, if the item is an array, call the function again to return the max item from that array.
In the end you should have always the max item and then in the last iteration, you could call the max from those results.
This does the trick:
function flatten($ar) {
$toflat = array($ar);
$res = array();
while (($r = array_shift($toflat)) !== NULL) {
foreach ($r as $v) {
if (is_array($v)) {
$toflat[] = $v;
} else {
$res[] = $v;
}
}
}
return $res;
}
$arr = array(array(128,300,140),10,15,array(130,array(500,650)));
echo max(array_flatten($arr));
EDIT: Updated flatten array with the one at How to "flatten" a multi-dimensional array to simple one in PHP?
<?php
$my_array = array(array(128,300,140),10,15,array(130,array(500,650)));
function findLargest($arr) {
$largest = 0;
foreach ($arr as $item) {
if (is_array($item)) {
$item = findLargest($item);
}
if ($item > $largest) {
$largest = $item;
}
}
return $largest;
}
echo "Largest is ".findLargest($my_array)."\n";
?>
function maximum($in)
{
if (!is_array($in)) $max = $in;
else foreach ($in as $element)
{
$elementMax = maximum($element);
if (isset($max)) $max = max($elementMax, $max); else $max = $elementMax;
}
return $max;
}

How do I select random values from an array in PHP?

I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.
I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?
$result = array();
foreach( array_rand($my_array, 8) as $k ) {
$result[] = $my_array[$k];
}
$array = array();
shuffle($array); // randomize order of array items
$newArray = array_slice($array, 0, 8);
Notice that shuffle() function gives parameter as a reference and makes the changes on it.
You could use array_rand to pick the keys randomly and a foreach to gather the objects:
$objects = array();
foreach (array_rand($my_array, 8) as $key) {
$objects[] = $my_array[$key];
}
What about?:
$count = count($my_array);
for ($i = 0; $i < 8; $i++) {
$x = rand(0, $count);
$my_array[$x];
}
I just found this in our code and was hoping to find a more readable solution:
$rand = array_intersect_key($all, array_flip(array_rand($all, $count)));
You can get multiple random elements from an array with this function:
function getRandomElements(array $array): array
{
$result = [];
$count = count($array);
for ($i = 0; $i < rand(0, $count); $i++) {
$result[] = rand(0, $count);
}
$result = array_unique($result);
sort($result);
return $result;
}

Categories