Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP arrays hold items of different type?

In other programming languages the definition of arrays is something which can hold similar kind of elements. For example if I declare something like int i[] it will store integers, but in PHP a single array seems to be holding strings and numbers together.

Will the number/integer be treated as string in such type of array in PHP?

like image 509
Rolen Koh Avatar asked Sep 20 '12 08:09

Rolen Koh


People also ask

What are different types of arrays supported in PHP?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

Are PHP arrays homogeneous?

The values assigned to the array are homogeneous in nature, it means the data type of all the values should be the same.

How many items can a PHP array hold?

There is no max on the limit of an array. There is a limit on the amount of memory your script can use.

What is multidimensional array in PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.


1 Answers

According to the PHP manual you can indeed store heterogeneous types inside a PHP "array" - scroll down to example 3.

Note that even though the example is about keys being ints or strings, the values assigned in the example are also both ints and strings, demonstrating that it is possible to store heterogeneous types.

Be aware that in the case of different-typed keys there is automatic casting involved so you may have surprising results in the case where e.g. a string contains a valid decimal representation.

like image 90
Joris Timmermans Avatar answered Sep 17 '22 18:09

Joris Timmermans