foreach loop - if greater than count or else - php

I have a foreach loop in php.
When the loop is greater than 2 items I would like to display some text instead of the loop. Is this possible?
For example: A loop of 2 or less items shows= item 1, item2
The loop of more items shows the text = Mulitple items.
The example code for indication:
$count++;
foreach($attValConfig as $attValConfigSingle) {
if ($attValConfigSingle["frontend_label"] == "LABELTEXT") {
echo ('<div class="attributes_row">Text</div>');
foreach($attValConfigSingle['values'] as $attValConfigSingleVal) {
if ($count++ > 2) { echo 'SomeNewText'; }
else echo "<option>"list of items"</option>";

I think you want to break in your if statement:
if ($count++ > 2) {
echo 'SomeNewText';
break;
}

You can count the array before looping:
if(count($attValConfigSingle['values']) > 2) {
// More than 2 items
echo "Lots of things";
} else {
// 2 items or less
foreach($attValConfigSingle['values'] as $value) {
// ...
}
}
Edit:
Maybe I didn't understand you correctly. If you want the text:
item 1, item 2, other items...
Then you need to use break to break out of your loop:
foreach($attValConfigSingle['values'] as $attValConfigSingleVal) {
if ($count++ > 2) {
echo 'SomeNewText';
break;
} else {
echo "<option>"list of items"</option>";
}
}

Just declare a variable in which you store your text built during the foreach loops. When you're out of it, print this string if count is less than 3, your other text otherwise.

Related

Nested Foreach() PHP

I need some assistance with my code logic:
The expected output of the following code is 1110, how to achieve that value?
<?php
$user_accepted_events = [1,2,3];
$all_events = [1,2,3,4];
//Nested foreach loop for testing if the user accepted an event
foreach ($all_events as $single_row) {
foreach ($user_accepted_events as $user_single_id) {
if ($single_row == $user_single_id) { //This prints expected value
print_r("1"); //User has accepted event
} else { //Here it logically print's 0 nine times
print_r("0"); //User has not accepted Event
}
}
}
//Expected Output is 1110
//Real Output is 100010001000
?>
Thanks.
As you have nested loops - it will compare each item against every nested item and most of them won't match - producing multiple results for each item.
Instead - use in_array() to check each item...
foreach ($all_events as $single_row) {
if ( in_array($single_row, $user_accepted_events)) {
print_r("1"); //User has accepted event
} else {
print_r("0"); //User has not accepted Event
}
}
You've got a logical error in your code: you are printing 1 or 0 for every permutation of both loops.
As there are 4 items in the outer loop and 3 in the inner, you are receiving 12 outputs.
Instead, keeping the same approach you have already adopted, you can capture whether the user has attended the event in a variable, and break if so.
Then once for each of the outer loops, output the result:
$user_accepted_events = [1,2,3];
$all_events = [1,2,3,4];
foreach ($all_events as $single_row) {
$hasAccepted = false;
foreach ($user_accepted_events as $user_single_id) {
if ($single_row == $user_single_id) {
$hasAccepted = true;
break;
}
}
print_r($hasAccepted ? 1 : 0);
}
Output:
1110

Insert static code block into a php "while loop" after "N" loops.

I have a php while loop, but I want to insert a "static" code block into it after the third item in the loop and then continue the loop after the static content. Can someone help me update my code to accomplish the "desired outcome" below?
My Code
$x = 0;
while($x <= 5) {
$contentItems = $relatedArray[$rand_keys[$x]];
$contentItems = explode('|', $contentItems);
echo '
<p><img class="faux" src="'.$contentItems[4].'"></p>
';
$x++;
}
Desired Outcome
Loop Content
Loop Content
Loop Content
**STATIC CONTENT**
Loop Content
Loop Content
Loop Content
Just add an if conditional inside of your while loop that checks against the index:
$x = 0;
while($x <= 5) {
// Will only trigger halfway through the loop
if ($x == 3) {
echo '**STATIC CONTENT**';
}
$contentItems = $relatedArray[$rand_keys[$x]];
$contentItems = explode('|', $contentItems);
echo '<p><img class="faux" src="'.$contentItems[4].'"></p>';
$x++;
}
Note that this will still output the original item at this position. If you want to replace it instead, you'll want to wrap everything related to $contentItems inside of an else conditional :)

php set a menu from an array for loop display

$array=array('menu1','menu2','menu3','menu4','menu5','menu6','menu7','menu8','menu9','menu10');
I storied some menu names into an array, Then output some like
in diffirent page, the menu always show 5 items and current page is always 2nd.
And if the current page is in this case, it will loop display menu1, menu2, menu3 after menu10.
foreach($array as $k=>$r){
if($r==$current){
$n=$k;//count current memu position
}
}
echo '<ul>';
foreach($d as $k=>$r){
if($n>1&&$n<7){//normal situation like first image
if($k==($n-1)){
echo '<li><a>'.$r.'</a></li>';
}else if($k==$n){
echo '<li class="current">'.$r.'</li>';
}else{
echo '<li><a>'.$r.'</a></li>';
}
}else{
//How to do in the case of the second image?
}
}
echo '</ul>';
I think you would also like the menu look like this when the current selection is menu1:
menu10
menu1 [selected]
menu2
menu3
menu4
Here is the algorithm. It looks confusing but I am sure you can figure it out.
$array=array('menu1','menu2','menu3','menu4','menu5','menu6',
'menu7','menu8','menu9','menu10');
$current = 'menu1';
$startIndex = array_search($current, $array)-1;
$total = count($array);
$result = array();
for($index = $startIndex ; $index <$startIndex+5; $index++){
$result[] = $array[($index+$total)%$total]; //using % operator
}
print_r($result);
Try this:
if($k==($n-1)){
echo '<li><a>'.$r.'</a></li>';
}else if($k==$n){
echo '<li class="current">'.$r.'</li>';
}else{
if($k >= count($d)-1)
echo ''<li><a>'.$d[$k-count($d)+1].'</a></li>';
else
echo ''<li><a>'.$r.'</a></li>';
}
This actually should work for both cases, so you can remove the big if statement and put this as the body of your foreach.

Count results inside foreach then store that value in a variable to be used elsewhere

How do you count the results inside a foreach then store that value in a variable to be used on another foreach.
Example. This foreach returns 5 items
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Now I want that the foreach above be counted and stored in say $totalitems and be used on another foreach. This second foreach also counts its results and store in $totalitems2. Something like this:
foreach ($xml->items as $item) { //Same source but they will be displayed separately based on a condition.
echo "$item->name";
echo "$item->address";
if_blah_blah_meet_condition_then_break;
}
So basically what I want here is to restrict the total number of items being displayed on both foreach combined. $totalitems and $totalitems2 should have the sum of 8. 8 is the number I want limit the items returned. Doesn't matter if the other foreach has more items than the other. 3 and 5. 4 and 4. 6 and 2. Etc.
How can I achieve this? Please advice.
Just use the simple iterator ++ methods. When you are on the second foreach, watch for when $i passes the number that you want to stop it.
Code:
$i = 0;
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
}
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
if ($i > 5) { // or whatever the number is
break;
}
}
$totalItems = count($xml->items);
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Just use count($xml->items) and that value in the condition, inside the loop.
It seems your array is stored in xml->items therefor, you only would have to save it in another variable if you want to store it.
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_one[] = $item;
}
}
//whatever changes you do to $xml->items
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_two[] = $item;
}
}
Like this you have the two new arrays totalItems_one and totalItems_two and you can get the number of items just doing count($totalItems_one) or count($totalItems_two) whenever you want.

too many rows created in drupal view

I have modified the tpl used for the grid view to show 3 columns of content, my only issue that the code below creates unneeded divs for the view. I have a maximum of 9 items that should be output in 3 rows, 3 per column. What's the best way to modify the code below? to prevent the extra divs from being output.
<?php foreach ($rows as $row_number => $columns): ?>
<div>
<?php foreach ($columns as $column_number => $item): ?>
<?php print $item; ?>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
I would drop that notation of foreach syntax (but I think that's pretty personal :-) )
You could use the modulo to check if you just had 3 columns (if I understood your question).
<?php
// I´m assuming that $column_number is a zero based index
// if thats not the case you should add a counter to keep track of column numbers or if it is in sequence but isn't zero based you could easily update the calculates based in your starting index
foreach ($rows as $row_number => $columns) {
foreach ($columns as $column_number => $item) {
if ($column_number == 0 || $column_number%3 == 0) {
print '<div>';
}
print $item;
if ($column_number == 2 || $column_number%3 == 2) {
print '</div>';
}
}
// prevent open div tags
$total_columns = count($columns);
if ($total_columns > 0 && ($total_columns < 3 || $total_columns%3 != 0)) {
print('<div>');
}
}
I've also dropped all those opening and closing tags of php for readability.

Categories