sam sam - 2 years ago 69
PHP Question

What kind of array does PHP use?

I can define an

in PHP like this:

$array = array();

In C++, we have two kinds of array.

  1. The first kind is a fixed size array, for example:

    int arr[4]; // here I define the size : 4

  2. The second kind is a dynamic sized array

    int vector arr=new vector <int>; // here I define a virtual size then if I exceed the virtual size, the size is multiple in heap (change size in run time)

What kind of array does PHP use? Are both kinds of arrays in PHP? If so, can you give me examples?

Answer Source

PHP is not as strict as C or C++. In PHP you don't need to specify the type of data to be placed in an array, you don't need to specify the array size either.

If you need to declare an array of integers in C++ you can do it like this:

int array[6];

This array is now bound to only contain integers. In PHP an array can contain just about everything:

$arr = array();
$arr[] = 1;
$arr[] = 2;
$arr[] = 3;
$arr[] = 4;
var_dump($arr);   //Prints [1,2,3,4]
$arr[] = 'hello world';   //Adding a string. Completely valid code
$arr[] = 3.14;   //Adding a float. This one is valid too
$arr[] = array(
           'id' => 128,
           'firstName' => 'John'
           'lastName' => 'Doe'
);  //Adding an associative array, also valid code
var_dump($arr);  //prints [1,2,3,4,'hello world',3.14, [ id => 128, firstName => 'John', lastName => 'Doe']]

If you're coming from a C++ background it's best to view the PHP array as a generic vector that can store everything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download