Php count element in array

Php count element in array

  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders

PHP Function Based

  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
Читайте также:  Основы синтаксиса языка php структура простейшей программы

PHP Date Based

  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?

PHP String Based

  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Html width 100 parent

PHP Class Based

PHP JSON Based

PHP File Systems Based

Источник

count

Подсчитывает количество элементов массива или что-то в объекте.

Для объектов, если у вас включена поддержка SPL, вы можете перехватить count() , реализуя интерфейс Countable. Этот интерфейс имеет ровно один метод, Countable::count() , который возвращает значение функции count() .

Пожалуйста, смотрите раздел «Массивы» в этом руководстве для более детального представления о реализации и использовании массивов в PHP.

Список параметров

Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.

count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.

Возвращаемые значения

Возвращает количество элементов в array_or_countable . Если параметр не является массивом или объектом, реализующим интерфейс Countable, будет возвращена 1. За одним исключением: если array_or_countable — NULL , то будет возвращён 0.

count() может возвратить 0 для переменных, которые не установлены, но также может возвратить 0 для переменных, которые инициализированы пустым массивом. Используйте функцию isset() для того, чтобы протестировать, установлена ли переменная.

Примеры

Пример #1 Пример использования count()

$a [ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
$result = count ( $a );
// $result == 3

$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
$result = count ( $b );
// $result == 3

$result = count ( null );
// $result == 0

$result = count ( false );
// $result == 1
?>

Пример #2 Пример рекурсивного использования count()

$food = array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));

// рекурсивный count
echo count ( $food , COUNT_RECURSIVE ); // выводит 8

// обычный count
echo count ( $food ); // выводит 2

Смотрите также

  • is_array() — Определяет, является ли переменная массивом
  • isset() — Определяет, была ли установлена переменная значением отличным от NULL
  • strlen() — Возвращает длину строки

Источник

PHP count() Function

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

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

Return Value: Returns the number of elements in the array
PHP Version: 4+
PHP Changelog: The mode parameter was added in PHP 4.2

More Examples

Example

Count the array recursively:

echo «Normal count: » . count($cars).»
«;
echo «Recursive count: » . count($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:

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 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.

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.

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.

Источник

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