skip to Main Content

I have a project, and as part of it I receive a form from the back-end, but I need to separate the number of questions, for example:
questionNumber = even number – separate half to the left and the rest to the right

questionNumber = odd number – half + 1 to the left and the rest to the right
(if I have 39 questions, 20 should go to the left and 19 to the right)

<tr>
td colspan="4" style="border: 1px solid black; width: 60%">{{ $k + 1 }}.
 $question['question'] }}</td>
td colspan="4" style="border: 1px solid black; width: 20%"></td>
td colspan="4" style="border: 1px solid black; width: 20%"></td>
</tr>

(the separation needs to be automatic because at any moment more questions can be added or removed)

I’m kinda of a starter in coding but I don’t know how to solve this

I tried using

@if (count($question) === 39)

but I found out after using this that it needs to be automatic because the number can change, after discovering that I came here to ask for help
(I never did php before)

2

Answers


  1. There is modulo "%" operator that returns the rest of the division, so if you do $question % 2 = 0, this will give you even numbers and $question % 2 = 1 return odd numbers of questions

    Login or Signup to reply.
  2. You can use the modulus operator (%) in PHP to determine if a number is even or odd. The modulus operator returns the remainder when one number is divided by another. If the remainder is 0, the number is even. If the remainder is not 0, the number is odd.

    if ($number % 2 == 0) {
        echo "$number is even";
    } else {
        echo "$number is odd";
    }
    

    Alternatively, you can use bitwise operator & to check if the last bit is set or not as well.

    if(($number & 1) == 0)
        echo "$number is even";
    else
        echo "$number is odd";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search