Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array length in a PHP class

Tags:

php

I'm new to object oriented programming in PHP. I made a simple order class with an array property. The method orderLength is not working. I'm getting an error:

Call to undefined method Order::count()

PHP:

<?php
    class Order {
        private $order = array();

        public function setOrder($wert) {
            foreach($wert as $value) {
                $this -> order[] = $value;
            }
        }

        public function orderLength() {
            $length = $this -> count(order);
            return $length;
        }

        public function returnOrder() {
            $value = $this -> order;
            return $value;
        }
    }

    $order = new Order;
    $order -> setOrder(array('Book1', 'Book2', 'Book3', 'Book4'));

    foreach ($order->returnOrder() as $value) {
        echo $value . " <br/>";
    }

    echo "The order length is: " . $order->orderLength();
like image 723
Greg Ostry Avatar asked Jul 25 '17 09:07

Greg Ostry


People also ask

How do you find the length of an array in PHP?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

How do I count the length of a object in PHP?

The count() function is used to count the elements of an array or the properties of an object. Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.

How do you get the length of an associative array in PHP?

If you want to find the length of an array in PHP, you can use the sizeof function and use the echo command along with it to print the length. The second method is using a function called: count().


2 Answers

Instead of $this->count(order) you can try with:

$length = count($this->order);
like image 165
hsz Avatar answered Sep 26 '22 13:09

hsz


Just return the count of $order:

public function orderLength() {
    return count($this->order);
}
like image 27
Vincent Decaux Avatar answered Sep 25 '22 13:09

Vincent Decaux