Reputation: 729
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?
Upvotes: 16
Views: 21769
Reputation: 21
Yes. A PHP array can have multiple data types in it. Also, you should note that arrays in PHP actually are represented in the form of key-value pairs, where the elements you will input into the array are values. You can explicitly define keys too, when entering elements into the array, but when you don't, PHP will use indices starting from 0. Example:
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
PHP will interpret as
array(4) {
["foo"]=>
string(3) "bar"
["bar"]=>
string(3) "foo"
[100]=>
int(-100)
[-100]=>
int(100)
}
Reference- http://php.net/manual/en/language.types.array.php
Upvotes: 2
Reputation: 10988
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.
Upvotes: 12
Reputation: 3546
Not going to put oil on the fire of the PHP Arrays are no arrays here… But yes, you can put different variable types (string, int, …) together in a PHP thing called Array.
Upvotes: 0
Reputation: 16905
You can store anything you want in an array.
Will the number/integer be treated as string in such type of array in PHP?
Not upon storing it. However, when you use a value as such, PHP will convert it. The usage of a value determines its interpretation. (Attention, the key is converted upon storing, however, if it is considered numerical)
Upvotes: 0