How to get array length in php

Array Length in PHP: Use the Count Function with Code Examples

PHP provides two identical functions whenever you need to get the length of an array. The count function is the most common method. You can also use the sizeOf function as it is just an alias of the count. I prefer the count function and would recommend avoiding the sizeOf function.

PHP Count Function Code Example

Counting Arrays in PHP

An array is a data structure to store multiple elements. Like any programming language, PHP provides helpful functions to work with arrays. We have seen many array functions in previous articles.

One common array operation is to determine its length, which is the number of elements an array has. There are two similar functions to get array length in PHP.

In this article, we’ll help you learn these functions. First, we’ll see the syntax and then elaborate it through examples. So let’s start.

Array length in PHP: count function

Description

The count function counts all elements in an array.

Syntax

count(array $value, int $mode = COUNT_NORMAL): int
  • $value – An array
  • $mode – An optional parameter with a default value of COUNT_NORMAL. We can pass COUNT_RECURSIVE (or 1) to count an array recursively. (Good for multi-dimensional arrays).
  • Returns the number of elements in $value.
  • If $value is not an array or object, the function returns 1.
  • If $value null, the functions returns 0.

Examples

Let’s put this theory into action by examples.

Pretty straightforward. Remember, there’s a second parameter $mode for altering the function’s behavior. We’ll pass COUNT_RECURSIVE to it and see how it is different than the default COUNT_NORMAL.

"Robert","Age"=>"22","Skills"=>array("MongoDB","Express","React","Node.js")); //Let's count this array using the count function (COUNT_NORMAL) and print it to console. echo "Length of \$arr (Using COUNT_NORMAL) is: ".count($arr)."\n"; //Let's count this array using the count function (COUNT_RECURSIVE) and print it to console. echo "Length of \$arr (Using COUNT_RECURSIVE) is: ".count($arr,COUNT_RECURSIVE); //OUTPUT //Length of $arr (Using COUNT_NORMAL) is: 3 //Length of $arr (Using COUNT_RECURSIVE) is: 7 ?> 

The difference is clear, COUNT_NORMAL counts the elements in the first level, which are (Name, Age, Skills). COUNT_RECURSIVE counts the elements in the second level, which are the elements of Skills.

Using Count Function to Get Length of 2nd Level Multidimensional PHP Arrays

The COUNT_RECURSIVE constant in the count PHP function mode parameter is a great way to count all the elements in a multidimensional array. I use it all of the time whenever I need to count an unknown length set of values coming from a database or API.

Check out the following example to see the count function going beyond second-level:

Читайте также:  Read csv delimiter python

Using Count for 2D PHP Array Length Code Example

Cool. Let’s now move on to the next function: sizeOf.

Array length in PHP: sizeOf function

sizeOf function is just an alias of the count function.

Description

The sizeOf function counts all elements in an array.

Syntax

sizeOf(array $value, int $mode = COUNT_NORMAL): int
  • $value – An array
  • $mode – An optional parameter with a default value of COUNT_NORMAL. We can pass COUNT_RECURSIVE (or 1) to count an array recursively. (Good for multi-dimensional arrays).
  • Returns the number of elements in $value.
  • If $value is not an array or object, the function returns 1.
  • If $value null, the functions returns 0.

Using the SizeOf function to find the length of PHP Array Code Example

Let’s revisit the same example to get array length in PHP, using sizeOf instead.

sizeOf function does have the $mode parameter. Let’s alter the function to count an array recursively.

The output is similar to the count function. You can use either of these functions to get array length in PHP.

BONUS: Common usage of array length in PHP

We do not leave a topic dangling by missing out on its practical use. Similarly, array length in PHP may have numerous uses, depends on the context you’re working. However, there is a frequently occurring practice you’ll encounter while coding.

The array length is mostly used in FOR loop to loop over an array. The idea is to terminate the loop once it reaches the end of an array, where the array length in PHP factors in.

 //OUTPUT // I am the First element // I am the Second element // I am the Third element // I am the Fourth element // I am the Last element ?> 

See how the count helps the loop to terminate at the right time. It also helps to get array elements by index. That’s it, we hope you’ve enjoyed the article.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these to learn more about arrays in PHP.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Источник

PHP Array Length Tutorial – How to Get an Array Size

PHP Array Length Tutorial – How to Get an Array Size

Arrays are a powerful data type in PHP. And knowing how to quickly determine the size of an array is a useful skill.

In this article I’ll give you a quick overview of how arrays work, and then I’ll dive into how to get the size of PHP arrays.

If you already know what arrays are, you can jump straight ahead to the How to get an Array size? section.

What is an Array in PHP?

Before we dive into getting an array size, we need to make sure we understand what an array is. An array in PHP is a variable type that allows you to store more than one piece of data.

For example, if you were storing a simple string, you would use a PHP string type:

$heading = 'PHP Array Length Tutorial';

However, if you wanted to store a few more pieces of separate data, you might consider using a couple of string variables.

$heading = 'PHP Array Length Tutorial'; $subheading = 'How to get an array size'; $author = 'Jonathan Bossenger'

That’s all well and good, but what if you need to store more data, and quickly recall any of those items elsewhere in your code? That’s where an array comes in handy. You can still store the individual pieces of data but using a single variable.

$post_data = array( 'PHP Array Length Tutorial', 'How to get an array size', 'Jonathan Bossenger' );

Each item in that array can be referenced by its numeric key. So instead of needing to recall the single variables, you could reference a single array item by its numeric key.

Читайте также:  Junit java intellij idea

For even more control, arrays also allow you to define your own array keys, using a string.

$post_data = array( 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => 'Jonathan Bossenger' );

This allows you to also reference the array item by its string key.

You can also define arrays using the new short array notation, which is similar to JavaScript:

$post_data = [ 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => 'Jonathan Bossenger' ];

Arrays can also be nested, forming more complex array variables:

$post_data = [ 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => [ 'name' => 'Jonathan Bossenger', 'twitter' => 'jon_bossenger', ] ]; 

And, you can recall a specific array value using its nested key:

However, if you find yourself regularly doing this, you might want to consider using objects rather than arrays.

Arrays are useful if you need to quickly gather and then use different pieces of related data in a function, or pass that data to another function.

By putting these pieces of data into an array, you have fewer variables defined, and it can make your code easier to read and understand later on. It’s also a lot easier to pass a single array variable to another function than it is to pass multiple strings.

$post_data = [ 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => [ 'name' => 'Jonathan Bossenger', 'twitter' => 'jon_bossenger', ] ]; $filtered_post_data = filter_post_data($post_data)

How to Get the Size of an Array in PHP

Usually when we talk about the size of an array, we’re talking about how many elements exist in that array. There are two common ways to get the size of an array.

The most popular way is to use the PHP count() function. As the function name says, count() will return a count of the elements of an array. But how we use the count() function depends on the array structure.

Let’s look at the two example arrays we defined earlier.

$post_data = array( 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => 'Jonathan Bossenger' ); echo count($post_data);

In this example, count($post_data) will result in 3. This is because there are 3 elements in that array: ‘heading’, ‘subheading’, and ‘author’. But what about our second, nested array example?

$post_data = [ 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => [ 'name' => 'Jonathan Bossenger', 'twitter' => 'jon_bossenger', ] ]; echo count($post_data);

Believe it or not, in this example, count($post_data) will also return 3. This is because by default the count() function only counts the top level array elements.

Читайте также:  Как называются указатели разметки html

If you take a look at the function definition, you will see that it accepts two arguments – the array to be counted, and a mode integer. The default value for that mode is the predefined constant COUNT_NORMAL , which tells the function to only count the top level array elements.

If we pass the predefined constant COUNT_RECURSIVE instead, it will run through all levels of nesting, and count those instead.

$post_data = [ 'heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => [ 'name' => 'Jonathan Bossenger', 'twitter' => 'jon_bossenger', ] ]; echo count($post_data, COUNT_RECURSIVE);

Now, the result of count($post_data, COUNT_RECURSIVE) will be, as expected, 5.

«But wait!», I hear you cry. «you mentioned there was another way?».

Well yes, the other function you can use is sizeof(). However, sizeof() is just an alias of count() , and many folks assume (rightly so) that sizeof() would return the memory usage of an array.

Therefore it’s better to stick with count() , which is a much more suitable name for what you are doing – counting elements in an array.

Thanks for reading! I hope you now have a better understanding of how to find the size of an array in PHP.

Источник

Get the length of an array in PHP.

This is a beginner’s guide on how to get the length of a PHP array. To count all of the elements in a PHP array, you can either use the count function or the sizeof function.

Counting the number of elements in a PHP array.

Do NOT use a loop to count the number of elements in array, as this would be extremely wasteful.

To count the number of elements in an array, you can use PHP’s native count function like so:

//An array of names. $names = array( 'John', 'Jason', 'Martina', 'Lisa', 'Tony' ); //Get the number of elements in the array by //using PHP's inbuilt count() function. $numElements = count($names); //Print it out. echo $numElements;

If you run the code snippet above, you will find that the output of count() is “5”. This is because there is five elements in the $names array.

Counting elements in a multidimensional array.

In some cases, you might need to count all of the elements in a multidimensional PHP array. To do this, you will need to use the count function’s second parameter, which is called mode.

To achieve this, we can simply pass the constant COUNT_RECURSIVE in as the second parameter:

//A multidimensional array. $arr = array( 1, 2, 10, array( 20, 21, 80 ) ); //Pass COUNT_RECURSIVE in as a second parameter. $numElements = count($arr, COUNT_RECURSIVE); //Print out the result echo $numElements;

Note that the code above will print out “7” instead of “6”. This is because the array containing 20, 21 and 80 is also considered to be an element (you’d be surprised by how many developers expect the length to be 6).

The difference between count and sizeof.

The count function and the sizeof function do the exact same thing. In fact, sizeof is merely an alias of the count function.

Personally, I would suggest that you stick to using the count function. This is because other programmers may expect the sizeof function to return the size of the array in bytes / memory.

Note that as of PHP 7.2, the count function will emit an E_WARNING error if you provide it with a variable that isn’t an array or a Countable object.

Источник

Оцените статью