Counting elements in multidimensional array? - php

I'm trying to count the nested elements in a multidimensional array. At first I thought I could use COUNT_RECURSIVE, but that counts everything. So I've tried two different approaches, none of them appeal to me. Is there a better way to do it?
$count = 0;
foreach ($topics as $t) {
foreach ($t as $c) {
$count++;
}
}
echo $count;
// or
echo (count($topics, COUNT_RECURSIVE)-count($topics));

function countNested($arr) {
return (count($arr, COUNT_RECURSIVE) - count($arr));
}

I would write this code:
$count = 0;
foreach ($topics as $t) {
$count+= count($t);
}
echo $count;

//The following example will count either one-dimensional or two-dimensional arrays
$values_count = (count($values, COUNT_RECURSIVE) - count($values)?:count($values));

Related

Create multiple span based on array

I have an array that looks like this:
$elm = 'a,b,c';
I need the values of the array so I use explode to get to them:
$q = explode(",",$elm);
I then would like to echo every single item into a span, so I make an array:
$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}
$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}
$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}
And then finally I output like this:
echo "<ul>";
for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
echo "<li>";
echo "<span>".$arr[$i]."</span>";
echo "<span>".$arr2[$i]."</span>";
echo "<span>".$arr3[$i]."</span>";
echo "</li>";
}
echo "</ul>";
The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.
The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";

foreach step 5 steps forward in an array

How can I step forward 5 steps when using foreach to output an arrays value? So In this the put will be 1, 5
$array = ("1","2","3","4","5","6","7","8","9");
foreach ($array as &$value) {
echo $value; //Where do I tell it to move 5 paces forward?
echo "<br/ >";
}
If a foreach loop cannot be used, I'm willing to use something else. I don't think "while" or "for" can be used here?
$array = array("1","2","3","4","5","6","7","8","9");
for($i=0; $i<count($array); $i+=5) {
echo $array[$i];
echo "<br/ >";
}
I would use a while loop. Just set an index outside of the loop, and add 5 to it on each iteration of the loop. When the index is larger than the length of the list, terminate the loop.
A more compact way to express these instructions is a for loop:
for ($i=0; $i<count($array); $i = $i+5)
If it is not numerically indexed
$count = -1;
foreach ($array as &$value) {
$count++;
if ($count%4 != 0) continue;
echo "$value".PHP_EOL;
}

Can use Array_sum or loop and make sum?

Have an array
array(array('a'=>'s','add'=>1),
array('a'=>'s1','add'=>2),
array('a'=>'s2','add'=>3)
...
...
);
I want to sum of all key add together.so result should be 6
Anyone know how to do this?
$sum = 0;
foreach($yourArray as $element) {
$sum += $element['add'];
}
echo $sum;
$sum = 0;
foreach($array1 as $array) {
$sum += $array['add'];
}
echo $sum; // will echo '6'
Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:
$total = 0;
foreach( $arrs as $arr )
{
$total += $arr['add'];
}
echo $total;
Where $arrs is the array you've defined above.
One liner echo array_sum(array_column($a, "add"));

Nested foreach loops for associative array combinations

I have an associative array as follows:
$myarray = array('a'=>array(), 'b'=>array(), 'c'=>array(), 'd'=>array());
I want to be able to get all pairs of elements in the array. If it wasn't an associative array, I would use nested for loops, like:
for($i=0; $i<count($myarray); $i++) {
for($j=$i+1; $j<count($myarray); $j++) {
do_something($myarray[$i], $myarray[$j]);
}
}
I have looked at using foreach loops, but as the inner loop goes through ALL elements, some pairs are repeated. Is there a way to do this?
Thanks!
The array_values() function returns an integer-indexed array containing all the values, so you can use it to obtain a list that you can iterate with a for.
Otherwise you can 'destroy' the array this way:
while($k = array_pop($my_array)) {
foreach($my_array as $j){
do_something($k, $j);
}
}
Try:
$keys = array_keys($myarray);
$c = count($myarray);
foreach ($keys as $k => $key1) {
for ($i = $k + 1; $i < $c; $i ++) {
dosomething($myarray[$key1], $myarray[$keys[$i]]);
}
}

How to find the foreach index?

Is it possible to find the foreach index?
in a for loop as follows:
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
$i will give you the index.
Do I have to use the for loop or is there some way to get the index in the foreach loop?
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
You can put a hack in your foreach, such as a field incremented on each run-through, which is exactly what the for loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).
A foreach will give you your index in the form of your $key value, so such a hack shouldn't be necessary.
e.g., in a foreach
$index = 0;
foreach($data as $key=>$val) {
// Use $key as an index, or...
// ... manage the index this way..
echo "Index is $index\n";
$index++;
}
It should be noted that you can call key() on any array to find the current key its on. As you can guess current() will return the current value and next() will move the array's pointer to the next element.
Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.
foreach(array_keys($array) as $key) {
// do stuff
}
You can create $i outside the loop and do $i++ at the bottom of the loop.
These two loops are equivalent (bar the safety railings of course):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
eg
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
I think best option is like same:
foreach ($lists as $key=>$value) {
echo $key+1;
}
it is easy and normally
PHP arrays have internal pointers, so try this:
foreach($array as $key => $value){
$index = current($array);
}
Works okay for me (only very preliminarily tested though).
I use ++$key instead of $key++ to start from 1. Normally it starts from 0.
#foreach ($quiz->questions as $key => $question)
<h2> Question: {{++$key}}</h2>
<p>{{$question->question}}</p>
#endforeach
Output:
Question: 1
......
Question:2
.....
.
.
.
Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as
$var = array(2,5);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
your output will be
2
5
in which case each element in the array has a knowable index, but if you then do something like the following
$var = array_push($var,10);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.
I solved this way, when I had to use the foreach index and value in the same context:
$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {
echo $letter; //Here $letter content is the actual index
echo $array[$letter]; // echoes the array value
}//foreach
I normally do this when working with associative arrays:
foreach ($assoc_array as $key => $value) {
//do something
}
This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:
foreach ($array as $indx => $value) {
//do something
}
foreach(array_keys($array) as $key) {
// do stuff
}
I would like to add this, I used this in laravel to just index my table:
With $loop->index
I also preincrement it with ++$loop to start at 1
My Code:
#foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
#endforeach

Categories