Seik
Seik

Reputation: 41

Foreach Counter as Array - PHP

I have 20 items in my foreach statement. I have been added counter using $index = 0; $index++

$index = 0;
foreach( $partialStructure as $map ) {

 // i am getting specific number of $tmp for specific subject ( member )
 $tmp = $this->getFieldValueString($field, $value, $subject, $map, $partialStructure);

 $array = array(
      $index => $index,
 );

if(count($array) < 20) {
   // redirect
} else {
  // do nothing
}

$index++;
}

In my case, i want to redirect member to another page if there are not 20 items. But when i check ['20'] and setup else, other 1 to 19 are still there, and redirect are going also if member have ['20'] exist.

How i can make it happend, if member have 20 items to dont redirect, and if there is less then 20 items to redirect?

Thanks !

Upvotes: 0

Views: 101

Answers (3)

Seik
Seik

Reputation: 41

I fix my code like this:

$counter = 0;
$tmp= array();
foreach( $partialStructure as $map ) {

 // i am getting specific number of $tmp for specific subject ( member )
 $tmp[] = $this->getFieldValueString($field, $value, $subject, $map, $partialStructure);

if($tmp['20'])
$counter++;


}
// out of foreach element, i setup this
if($counter == 0) {
   header("Location: /members/edit/profile?redirect=1");     
}

$counter will give you 1, if tmp['20'] is there, else, you can do the redirect...

Upvotes: 0

poloroid
poloroid

Reputation: 9

Try using the php function count() to get the number of elements in your array ;) https://www.php.net/manual/en/function.count.php

Upvotes: 1

1321941
1321941

Reputation: 2170

You can just check the length of the array rather than computing the length through iterating through it.

if(count($array)) < 20) {
  //redirect
}else{
  //do whatever you need to do
}

count()

Upvotes: 1

Related Questions