How to calculate how many items in a foreach?
I want to count total rows.
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
If you just want to find out the number of elements in an array, use count. Now, to answer your question...
How to calculate how many items in a foreach?
$i = 0;
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
$i++;
}
If you only need the index inside the loop, you could use
foreach($Contents as $index=>$item) {
// $index goes from 0 up to count($Contents) - 1
// $item iterates over the elements
}
You don't need to do it in the foreach.
Just use count($Contents).
count($Contents);
or
sizeof($Contents);
foreach ($Contents as $index=>$item) {
$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
There's a few different ways you can tackle this one.
You can set a counter before the foreach() and then just iterate through which is the easiest approach.
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
Try:
$counter = 0;
foreach ($Contents as $item) {
something
your code ...
$counter++;
}
$total_count=$counter-1;
$Contents = array(
array('number'=>1),
array('number'=>2),
array('number'=>4),
array('number'=>4),
array('number'=>4),
array('number'=>5)
);
$counts = array();
foreach ($Contents as $item) {
if (!isset($counts[$item['number']])) {
$counts[$item['number']] = 0;
}
$counts[$item['number']]++;
}
echo $counts[4]; // output 3
foreach ($array as $value)
{
if(!isset($counter))
{
$counter = 0;
}
$counter++;
}
//Sorry if the code isn't shown correctly. :P
//I like this version more, because the counter variable is IN the foreach, and not above.
You can do sizeof($Contents) or count($Contents)
also this
$count = 0;
foreach($Contents as $items) {
$count++;
$items[number];
}
Imagine a counter with an initial value of 0.
For every loop, increment the counter value by 1 using $counter = 0;
The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}
Try that.
$index = 0;
foreach( $array ?? [] as $index=> $item ) {
$index++;
$data[] = array(
'id' =>$index
);
}
Related
I've been stuck on this for like 2 days, and I know it's much more simpler than I think it is..
I have a foreach loop that goes like this.
foreach($appointments as $appointment){
$list = $appointment['techs']
}
The $appointment['techs']; comes out of the database like this.
a:2:{i:0;s:1:"1";i:1;s:2:"12";}
My question is, how to I get loop through appointments and then show the users that are assigned to each appointment...
The desired output should look like this,
{ resource : 1, event : 1},{ resource : 12, event : 1}
I've literally tried everything! Any help would be greatly appreciated.
$array = [];
$string = 'a:2:{i:0;s:1:"1";i:1;s:2:"12";}';
$arr = (unserialize($string));
foreach ($arr as $item){
array_push($array, json_encode(['resource'=> $item, 'event'=>1]));
}
$i = 0;
$numItems = count($array);
foreach ($array as $item) {
if (++$i === $numItems) {
echo $item;
}
else{
echo $item.',';
}
}
// Output: {"resource":"1","event":1},{"resource":"12","event":1}
The PHP command unserialize it's what you are looking for.
foreach($appointments as $appointment){
$list = unserialize($appointment['techs']);
}
Using PHP and MySQL I have generated two arrays. I would like to loop through these arrays, retrieve data from both and display together in one sentence.
foreach ($items as $item) {
if(isset($item->item_title)) {
$itemTitle = $item->item_title;
}
// var_dump($itemTitle);
// string(7) "Halfway" string(5) "Story" string(6) "Listen"
}
foreach ($aData["Items"]["Item"] as $a) {
if (isset($a['description'])) {
$aDescription = $a['description'];
}
// var_dump($aDescription );
// string(4) "Good" string(6) "Strong" string(2) "OK"
}
?>
Desired result;
The title is Halfway and the description is Good.
The title is Story and the description is Strong.
The title is Listen and the description is OK.
// etc
// etc
Is it possible to nest the foreach loops, or is there a better more efficient way?
Please try this way. Hope this help!!
foreach ($items as $index => $item) {
if(isset($item->item_title)) {
$itemTitle = $item->item_title;
echo 'The title is '.$itemTitle;
}
if(isset($aData["Items"]["Item"][$index]['description']) {
$itemDescription = $aData["Items"]["Item"][$index]['description'];
echo ' and the description is '.$itemDescription;
}
echo '<br>';
// The title is Halfway and the description is Good.
}
You can merge those two foreach loops using a simple for loop, like this:
$count = count($items) >= count($aData["Items"]["Item"]) ? count($aData["Items"]["Item"]) : count($items);
for($i = 0; $i < $count; ++$i){
if(isset($item[$i]->item_title)) {
$itemTitle = $item[$i]->item_title;
}
if (isset($aData["Items"]["Item"][$i]['description'])) {
$aDescription = $aData["Items"]["Item"][$i]['description'];
}
// your code
}
Sidenote: The above code assumes that two arrays $items and $aData["Items"]["Item"] have unequal number of elements, though this will work for equal number of elements as well. If you're sure that these two arrays will always have equal number of elements, then refactor the $count = ... ; statement in the following way,
$count = count($items);
or
$count = count($aData["Items"]["Item"]);
and use this $count variable in for loop.
Try this hope this will help you out.
Note: Here i am assuming both array's have same indexes.
$items
$aData["Items"]["Item"].
If not you can do array_values($items) and array_values($aData["Items"]["Item"])
foreach ($items as $key => $item)
{
if (isset($item->item_title) && isset($aData["Items"]["Item"][$key]['description']))
{
$itemTitle = $item->item_title;
echo sprinf("The title is %s and the description is %s",$itemTitle,$aData["Items"]["Item"][$key]['description']);
echo PHP_EOL;
}
}
I have a loop that needs to go through each item. So naturally a foreach loop seems like the best idea. However, I need to add an element to the array as it iterates. I tried the following without any luck.
foreach ($allitems as $item) {
//Do some stuff here
if ($value === true)
$allitems[] = 'New item';
}
I found out the foreach loops seem to use a referenced copy of the array, so editing the array does not register in the loop.
A workaround is to use the older styled while loops as follows:
while (list($key, $item) = each($allitems)) {
//Do some stuff here
if ($value === true)
$allitems[] = 'New item';
}
Clearly a foreach loop would be nicer and more efficient. Is it possible? Or is the while structure the best possible solution.
Yeah, it is possible:
foreach ($allitems as &$item) {
//Do some stuff here
if ($value === true)
$allitems[] = 'New item';
}
According to the docs, you need to pass a reference (using the & in front if $item)
More concrete example:
<?php
$allitems = array(1,2,3,4);
foreach ($allitems as &$item) {
echo $item."\n";
if ($item == 2) {
$allitems[] = "Blah";
}
}
?>
This outputs (using php from commandline)
1
2
3
4
Blah
It seems like an ordinary for loop would be best for this:
for ($i = 0; $i < count($array); $i++) {
// Do some stuff here that calculates $value from $array[$i]
if ($value === true) {
$array[] = "New Element";
}
}
You could do foreach...like this....
But it adds more code...so its not any better than your while loop..
foreach($array as $val){
if($val=="check"){$append[]="New Item";}
}
$array = array_merge($array, $append);
Of course, if you want your structure maintained..then rather use array_push
How to read the array below. For example i would like to set the 'actual_cash' to some other value. PLease help I am new to PhP.
$Cashups[0]['actual_cash'] = 50.22;
To change the first instance of actual_cash.
$Cashups[1]['actual_cash'] = 100.22;
To chance the second instance, and so on.
To loop through this array, you can do something like:
foreach($Cashups as &$c)
{
$c['actual_cash']=500.00;
}
Which would change al the actual_cash instances to 500.00
You can use foreach to iterate array
foreach($Cashups as $key => $value)
{
$value['actual_cash']='newval';
}
if you have only two items in array you could also do this
$Cashups[0]['actual_cash']='someval';
$Cashups[1]['actual_cash']='someval';
foreach($Cashups as $item){
$item['actual_cash'] = $mynewvalue;
}
using for loop:
for($i = 0; $i < count($Cashups); $i++) {
$Cashups[$i]['actual_cash'] = $yourValue;
}
using foreach loop:
foreach($Cashups as &$c) {
$c['actual_cash'] = $yourValue;
}
Try something like this
foreach($Cashups as &$cashup){
// referencing $cashup to change it's value
$cashup = 'new value';
}
Using a regular for loop, it's possible to comapred the current index with the last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach? I mean something like this.
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = islast(); //boolean true/false
}
If not, is there at least a way to know the current index of the current iteration like $iteration = 5, so I can manually compare it to the length of the $array?
The counter method is probably the easiest.
$i = count($array);
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = !(--$i); //boolean true/false
}
You can use a combination of SPL’s ArrayIterator and CachingIterator class to have a hasNext method:
$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
$last_iteration = !$iter->hasNext();
}
Here are a few methods for this;
$items = ["Bhir", "Ekky", null, "Uych", "foo"=>"bar"];
$values = array_values($items);
// Bhir, Ekky, Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = isset($values[$i + 1]);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = array_key_exists($i + 1, $values);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$i = count($values);
foreach ($items as $item) {
print("$item");
$next = !!(--$i);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$items = new \CachingIterator(new \ArrayIterator($items));
foreach ($items as $item) {
print("$item");
$next = $items->hasNext();
if ($next) {
print(", ");
}
}
No, you need to have a counter and know the amount of items in the list. You can use end() to get the last item in an array and see if it matches the current value in your foreach.
If you know that the values of the array will always be unique, you can compare the current $item to end($array) to know if you're at the last item yet. Otherwise, no, you need a counter.
You can get the key and the value in foreach() like this:
foreach($array as $key=>$value) { ... }
Alternatively, you could do a count() of the array so you know how many items there are and have an incrementing counter so that you know when you've reached the last item.
end($array);
$lastKey = key($array);
foreach($array as $key => $value) {
if ($key === $lastKey) {
// do something endish
}
}
The valid() method says if the ArrayIterator object has more elements.
See:
$arr = array("Banana","Abacaxi","Abacate","Morango");
$iter = new ArrayIterator($arr);
while($iter->valid()){
echo $iter->key()." - ".$iter->current()."<br/>";
$iter->next();
}