0

I have the following php code where it goes through a loop and push elements to an array. I wanted to count elements in that array at the end of the loop. But it is not showing anything. Can someone please help me here?

<?php
  $i=0;
  $uphPerOperator = [];
    while($i<10){
     $uphPerOperator = array_push($uphPerOperator,$i);
     $i++;
    }
  $uphArrayCount = count($uphPerOperator);   
  echo $uphArrayCount; ?>
1
  • 4
    You use array_push the wrong way, see the php manual to see how this function works and what it is supposed to return. Commented Sep 13, 2019 at 2:44

1 Answer 1

1

I got the code working by changing it following way

<?php
  $i=0;
  $uphPerOperator = [];
    while($i<10){
     array_push($uphPerOperator,$i);
     $i++;
    }
  $uphArrayCount = count($uphPerOperator);   
  echo $uphArrayCount; ?>

Basically I changed $uphPerOperator = array_push($uphPerOperator,$i); to array_push($uphPerOperator,$i); and it works

Sign up to request clarification or add additional context in comments.

2 Comments

A more idiomatic way to write it is $uphPerOperator[] = $i;
When answering you own answer you can mark it as accepted. I think you should also add link to the official documentation of tge array_push function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.