Get size of php array

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.

Источник

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.

Читайте также:  Php include common inc

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.

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.

Читайте также:  Python print вывод в файл

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.

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.

Источник

PHP sizeof() Function

The sizeof() function returns the number of elements in an array.

The sizeof() function is an alias of the count() function.

Syntax

Parameter Values

  • 0 — Default. Does not count all elements of multidimensional arrays
  • 1 — Counts the array recursively (counts all the elements of multidimensional arrays)

Technical Details

More Examples

Example

Count the array recursively:

echo «Normal count: » . sizeof($cars).»
«;
echo «Recursive count: » . sizeof($cars,1);
?>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Читайте также:  Engine modules functions php dle

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP array length or size count

This will output 4 as there are four elements inside the array.

You can use sizeof function also to determine the number of values

$value= array(2,5,6,8,9); 
echo "size of array = ".sizeof($value)."
"; // Output = 5

With COUNT_RECURSIVE (or 1)

We can use optional parameter mode to recursively count the array. ( Total number of keys up to 2 levels )

"apple","quantity"=>2), array("product"=>"Orange","quantity"=>4), array("product"=>"Banana","quantity"=>5), array("product"=>"Mango","quantity"=>7), ); echo count($a); // Output = 4 echo "
"; echo count($a,1); // Output = 12 ?>
echo sizeof($a); // Output = 4 echo "
"; echo sizeof($a,1); // Ouput = 12

Words Count ( Sample projects using sizeof function)

we can use sizeof function to count number of words present in paragraph. Here are the steps involved.

1. Store the paragraph of text in a string variable 
2. Break the variable and create an array by using explode() function with space as delimiter
3. Count the number of elements present in the array.

plus2net.com

Click here for More on PHP Array functions

  • Array functions in PHP
  • array : Creating an Array
  • Multidimensional array : Creating and displaying
  • array_diff Difference of two arrays
  • array_count_values counting the frequency of values inside an array
  • count : sizeof Array Size or length
  • array_push : Adding element to an Array
  • array_merge : Adding two arrays
  • array_sum : Array Sum of all elements
  • array_keys : To get array of keys from an array
  • max Getting the maximum or Minimum value of elements in an array
  • current Value of present cursor element in an array
  • reset Moves the internal pointer to first element
  • end Moves the internal pointer to last element
  • Array checkbox
  • array_map : Using user defined and native function to each element of an array
  • current : Returns current element
  • reset : Move cursor to first element
  • end : Move cursor to last element
  • next : Move cursor to next
  • prev : Move cursor to previous element
  • in_array : IN Array to search for elements inside an array
  • is_array : To check the variable is array or not
  • array_rand : Random elements of Array
  • array_unique : Array Unique values
  • Breaking of strings to create array using split command
  • Session Array to maintain data in different pages
  • unset : Deleting elements of an array by using its key or value
  • sort: sorting of PHP array
  • usort: Sorting array by using user defined function
  • Displaying the elements of an array
  • Filtering elements and returning new array based on callback function
  • Applying user function to each element of an array
  • http_build_query: generate query string using elements to pass through URL

Источник

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