There are several ways to initialize an array with values in PHP:
- Using array() function: You can use the array() function in PHP to initialize an array with values. Each value is separated by a comma and enclosed in parentheses.
$myArray = array(1, 2, 3, 4, 5);
- Using short array syntax: Since PHP 5.4, you can use the short array syntax to initialize an array. Instead of using the array() function, you can directly define the values within square brackets.
$myArray = [1, 2, 3, 4, 5];
- Associative arrays: If you want to initialize an array with key-value pairs, you can use the array() function or the short array syntax.
$myArray = array("name" => "John", "age" => 25, "city" => "New York");
or
$myArray = ["name" => "John", "age" => 25, "city" => "New York"];
- Multidimensional arrays: If you need to initialize a multidimensional array, you can nest arrays within arrays.
$myArray = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
These are the common ways to initialize arrays with values in PHP. You can choose the one that suits your needs and coding style.