length of array 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:
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:
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
Привет. В PHP довольно часто приходится работать со строками и массивами и почти во всех случаях требуется узнать их длину (length). Вполне типичная ситуация и для нее есть встроенные функции в PHP. Но есть некоторые нюансы, к примеру то, что одна из функций, которая показывает длину строки — srtlen считает не количество символов в тексте, а количество байт, который занимает каждый символ. Если латинский символ занимает 1 байт, то на кириллице он займет 2 байта. Об этом я же упоминал в статье по теме: как обрезать текст по количеству слов и символов. Но сейчас постараемся рассмотреть некоторые примеры более детально.
Узнать длину строки в PHP
Первая функция, которая будет вычислять длину строки в PHP, будет strlen.
$str = «Hello World»; echo strlen($str); // 11 символов вместе с пробелом
А если мы напишем примерно то же самое, но на русском, то получим такой вариант:
$str = «Привет Мир»; echo strlen($str); // 19 символов вместе с пробелом
В этом случае, как я уже говорил ранее, каждый символ займет 2 байта + 1 байт — это пробел. В итоге мы получим не совсем то, что ожидали. Поэтому в случае с кириллицей, чтобы определить длину строки, следует использовать другие функции. Первая — mb_strlen
$str = «Привет Мир»; echo mb_strlen($str); // 10 символов вместе с пробелом
В этом случае подсчет символов в строки будет одинаковым как на английском, так и на русском языках. Даже если символ занимает несколько байт, то будет посчитан, как один. Так же есть еще одна функция, чтобы узнать длину строки в символах — iconv_strlen
$str = «Привет Мир»; echo iconv_strlen($str); // 10 символов вместе с пробелом
iconv_strlen учитывает кодировку строки, ее можно указать вторым параметром. Если она не указана, то кодировка будет внутренней. То есть самого файла.
echo iconv_strlen($str, «UTF-8»);
Если возникла необходимость проверить длину строки без пробелов, то потребуется дополнительная функция str_replace
Узнать длину массива в PHP
функция, которая позволяет узнать длину массива в PHP — count.
То же самое будет с массивом, где есть ключи и значения.
strlen() | Подсчет количества байт в строке |
mb_stren() | Подсчет символов в строке |
iconv_strlen() | Подсчет символов строки с учетом кодировки |
count() | Подсчет элементов массива |
На этом можно завершить. Теперь вы можете самостоятельно узнать длину строки в PHP и определить длину массива. А если возникнут вопросы, задавайте их в комментариях.
count
(PHP 4, PHP 5, PHP 7, PHP 8)
count — Подсчитывает количество элементов массива или чего-либо в объекте
Описание
Подсчитывает количество элементов массива или чего-то в объекте.
Смотрите раздел Массивы в этом руководстве для более детального представления о реализации и использовании массивов в PHP.
Список параметров
Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.
count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования count()
Результат выполнения данного примера:
var_dump ( count ( null ));
var_dump ( count ( false ));
?>
Результат выполнения данного примера:
Результат выполнения данного примера в PHP 7.2:
Результат выполнения данного примера в PHP 8:
Пример #3 Пример рекурсивного использования count()
Смотрите также
User Contributed Notes 17 notes
[Editor’s note: array at from dot pl had pointed out that count() is a cheap operation; however, there’s still the function call overhead.]
If you are on PHP 7.2+, you need to be aware of «Changelog» and use something like this:
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.
$arr [ ‘__been_here’ ] = true ;
to end the debate: count() is the same as empty()
results on my computer:
count : double(0.81396999359131)
empty : double(0.81621310710907)
using isset($test[0]) is a bit slower than empty;
test without adding value to the array in function ****Test: still the same.
A function of one line to find the number of elements that are not arrays, recursively :
Get maxWidth and maxHeight of a two dimensional array.
Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays
You can not get collect sub array count when there is only one sub array in an array:
$a = array ( array (‘a’,’b’,’c’,’d’));
$b = array ( array (‘a’,’b’,’c’,’d’), array (‘e’,’f’,’g’,’h’));
echo count($a); // 4 NOT 1, expect 1
echo count($b); // 2, expected
For a Non Countable Objects
Warning: count(): Parameter must be an array or an object that implements Countable in example.php on line 159
#Quick fix is to just cast the non-countable object as an array..
As I see in many codes, don’t use count to iterate through array.
Onlyranga says you could declare a variable to store it before the for loop.
I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.
You can not get collect sub array count when use the key on only one sub array in an array:
$a = array(«a»=>»appple», b»=>array(‘a’=>array(1,2,3),’b’=>array(1,2,3)));
$b = array(«a»=>»appple», «b»=>array(array(‘a’=>array(1,2,3),’b’=>array(1,2,3)), array(1,2,3),’b’=>array(1,2,3)), array(‘a’=>array(1,2,3),’b’=>array(1,2,3))));
echo count($a[‘b’]); // 2 NOT 1, expect 1
echo count($b[‘b’]); // 3, expected
To get the count of the inner array you can do something like:
$inner_count = count($array[0]);
echo ($inner_count);
About 2d arrays, you have many way to count elements :
Criada para contar quantos níveis um array multidimensional possui.
/* Verifica se o ARRAY foi instanciado */
if (is_setVar($matrix))<
/* Verifica se a variável é um ARRAY */
if(is_array($matrix))<
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs.
If you want to know the sub-array containing the MAX NUMBER of values in a 3 dimensions array, here is a try (maybe not the nicest way, but it works):
$cat_poids_max[‘M’][‘Seniors’][] = 55;
$cat_poids_max[‘M’][‘Seniors’][] = 60;
$cat_poids_max[‘M’][‘Seniors’][] = 67;
$cat_poids_max[‘M’][‘Seniors’][] = 75;
$cat_poids_max[‘M’][‘Seniors’][] = 84;
$cat_poids_max[‘M’][‘Seniors’][] = 90;
$cat_poids_max[‘M’][‘Seniors’][] = 100;
//.
$cat_poids_max[‘F’][‘Juniors’][] = 52;
$cat_poids_max[‘F’][‘Juniors’][] = 65;
$cat_poids_max[‘F’][‘Juniors’][] = 74;
$cat_poids_max[‘F’][‘Juniors’][] = 100;
PHP Array Length: How to Find Array Length in PHP [With Examples]
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
What Are PHP Arrays?
Below is the example we can consider as key and value pair:
Note: we categorize Arrays as “indexed array” and “associative array” based on the key stipulation. The Indexed array has a default index that starts with ‘0’.The associative array includes the user-defined key index. We can use the keys for strings and natural numbers.
How to create an Array in PHP?
$animals = array(“Bear”, “Leopard”, “Tiger”);
// loop through the array
$animals = array(“Leopard”=>”Wild”, “Cow”=>”Domestic”, “Lion”=>”Wild”);
// loop through associative array and get key-value pairs
//two-dimensional array definition declaration
// two-dimensional array iteration declaration
Below is the image as a perfect example for the three-dimensional array:
PHP | sizeof() Function
The sizeof() function is a built-in function in PHP, and we can use it to count the number of elements present in an array countable object.
int sizeof(array, mode);
Parameter: As per the above syntax example, this function accepts two parameters.
How to Check if a Value Exists in an Array in PHP
Check if the value exists in an array in PHP
Step 1 – Use the PHP in_array() function to test if a value exists in an array or not.
Step 2 – Define the in_array() function
As per the below code snippet Example:
$zoo = array(“Leopard”, “Tiger”, “Elephant”, “Zebra”, “Rhino”, “Dear”);
echo “The elephant was found in the zoo.”;
echo “The tiger was found in the zoo.”;
How to Count all Elements or Values in an Array in PHP
We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array.
Below is the code snippet:
$days = array(“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”);
// Printing array size
How to Print or Echo all the Values of an Array in PHP
Use the PHP foreach loop.
Below is the code snippet:
$colors = array(“Yellow”, “Purple”, “Red”, “Brown”, “Skyblue”);
// Loop through colors array
How to Display Array Structure and Values in PHP
Use the PHP print_r() or var_dump() Statement
Below is the code snippet example we can consider for this:
$cities = array(“Canada”, “Australia”, “New Jersey”);
// Print the cities array
How to Remove the Last Element From an Array in PHP
Use the PHP array_pop() function
Below is the code snippet Example to explain how this function runs:
$sports = array(“Tennis”, “Cricket”, “BasketBall”, “Badminton”);
// Deleting last array item
Conclusion
If you’re interested to learn more about PHP, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.