-1

I need to get the count of the authors on the WordPress page. First of all, this question does not touch WordPress syntax or something more about this CMS. The question is strictly about php algorithms.

So, I have the 10 elements get by the method foreach. And now I must put they in the array $getcount to get they count by array method count in php language.

For some reasons method count does not work, because I always get the else result.

<?php foreach ($coauthors_meta as $key ) :  
    $getcount = array($key);
    if (count($getcount) > 1) echo '<div class="privv">Hello!</div>';
    else echo 'Empty';
<?php endforeach; ?>

P.S. Array method foreach ($coauthors_meta as $key ) work fine and dispay all authors on the page. So the problem is hidding in other thing.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Sviat Kuzhelev
  • 1,758
  • 10
  • 28
  • Possible duplicate of [How to add elements to an empty array in PHP?](https://stackoverflow.com/questions/676677/how-to-add-elements-to-an-empty-array-in-php) – mickmackusa Jan 18 '18 at 21:58

3 Answers3

5

You are creating an array with one element every time and then checking to see if it has more than one element.

<?php foreach ($coauthors_meta as $key ) :  
    $getcount = array($key); // << always makes an array with one element
    // count will always be 1 so the else condition will always happen
    if (count($getcount) > 1) echo '<div class="privv">Hello!</div>';
    else echo 'Empty';
<?php endforeach; ?>

Change :

$getcount = array($key);

To

$getcount[] = $key;
ryantxr
  • 4,119
  • 1
  • 11
  • 25
2

Problem:- You are assigning only single value to $getcount variable inside foreach()(variable re-created again and again and the current value assigned to it).

Solution:- Reconstruct logic like below:-

//empty array declaration
<?php $getcount = [];?>
<?php foreach ($coauthors_meta as $key ) :  
    $getcount[] = $key;//assign values to the array
    if (count($getcount) > 1) echo '<div class="privv">Hello!</div>';
    else echo 'Empty';
<?php endforeach; ?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

What you are doing wrong (as it seems), is that you are creating a new array every foreach loop and assigning 1 of the keys into it:

<?php foreach ($coauthors_meta as $key ) :  
    $getcount = array($key); // <---- You are creating a new array!
    if (count($getcount) > 1) echo '<div class="privv">Hello!</div>';
    else echo 'Empty';
<?php endforeach; ?>

To fix this, simply define your array before the foreach, and push the value to the array:

<?php 
    $getcount = array();
    foreach ($coauthors_meta as $key ) :  
    $getcount[] = $key;
    if (count($getcount) > 1) echo '<div class="privv">Hello!</div>';
    else echo 'Empty';
<?php endforeach; ?>

And now it should work! :)

Ivo Silva
  • 367
  • 2
  • 13