-2

I have an integer value which will always be a whole number, called $post_count

I want to divide $post_count by 2. So if it's an even number, it will always produce a whole result. E.g if $post_count = 8 then I want the result of my arithmetic to be 4.

However if it's an odd number, I wish to presented with the rounded-up number. So if $post_count = 7, I would still want the answer to be 4, because the maths is =

7 / 2 = 3.5
3.5 rounded up = 4

I've written the following code but I am wondering if it's possible to reduce this quite lengthy code into something simpler?

$post_count = $the_query->found_posts;
$post_count = $post_count / 2;
$post_count = round($post_count);
Francesca
  • 26,842
  • 28
  • 90
  • 153

3 Answers3

1

You can use ceil -

$post_count = ceil( $the_query->found_posts / 2 );

If $the_query->found_posts = 7 then it will print 4. ceil will always return the next bigger integer of the current number.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0
<?php
$posts = 7;
echo round($posts/2);
// 4
take
  • 2,202
  • 2
  • 19
  • 36
0

You can do like this:

$post_count = round($the_query->found_posts/2);
Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37