Find last element of if inside for loop PHP
Get the solution ↓↓↓I am writing a PHP code to loop numbers from 5 to 41 with if condition inside. I want to detect the last element in if condition not in the whole loop.
This is my code
for($i=5;$i<=41;$i++){
$true[$i] = $Class->isTrue($i); // The class return TRUE OR FALSE
if($true[$i]{
echo '<hr>'; // Print thematic break if not the last element
}
}
Answer
Solution:
Try this instead (notice x != 0)
for($i=5,$x=0;$i<=41;$i++){
$true[$i] = $Class->isTrue($i); // The class return TRUE OR FALSE
if($true[$i]{
if($x != 0){ echo '<hr>'; }
x++;
// Print element here
}
}
Answer
Solution:
So I found a solution I think for my problem, instead of trying to catch the last element, I catch the first one then print the thematic break above all but the first element. so like this I don't print it below the last element as I want to do.
My code
for($i=5,$x=0;$i<=41;$i++){
$true[$i] = $Class->isTrue($i); // The class return TRUE OR FALSE
if($true[$i]{
if($x == 0){ echo '<hr>'; }
x++;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.