15

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?

2

4 Answers 4

12

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.

2
  • 1
    You are correct, but the question was about storing different type of values, not keys. Not sure why this was downvoted though.
    – phant0m
    Sep 21, 2012 at 21:10
  • @phant0m - I actually missed the title of the example completely, I was looking at the right-hand side of that example. Answer clarified, thank you. Sep 25, 2012 at 10:09
2

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

0

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)

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.