Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of array does PHP use?

Tags:

arrays

php

I can define an array 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]; // 4 ints, hardcoded size
    
  2. The second kind is a dynamic sized array

    std::vector<int> v; // can grow and shrink at runtime
    

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

like image 843
sam Avatar asked May 31 '16 10:05

sam


1 Answers

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.

like image 192
dimlucas Avatar answered Sep 19 '22 22:09

dimlucas