Длина массива array php

Длина массива array php

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

Читайте также:  Закрепить header при прокрутке css

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

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

Читайте также:  Функция алгоритм евклида python

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.

Читайте также:  Javascript найти корень числа

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.

Источник

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