How To Initialize An Array In PHP

What we are going to see through this article is How To Initialize An Array In PHP. Arrays are sets of data. A variable can only hold one object at a time.

Rows can hold multiple items. Most programming languages ​​have different types of collections, including lists, maps, rows, rows, layers, and doubles.

 There are three types of array supported in PHP:

  • Indexed arrays: Arrays having a numeric index.
  • Associative arrays: Arrays having named keys.
  • Multidimensional arrays: It contains one or more array in particular array.

This is the syntax for creating an empty array is given below:

$emptyArray = []; 
$emptyArray = array();
$emptyArray = (array) null;
How To Initialize An Array In PHP

How to Initialize an Array in PHP

<?php

$emptyArray = (array) null;

var_dump($emptyArray);
?>

Output

This is an output of the empty array will show below:

array(0) {
}

How to Initialize an Array in PHP

<?php

/* method to create Empty array. */
$firstempty = [];
echo "Created First empty array <br>";
	
/* method to create Second Empty array. */
$second = array( );
echo "Created second empty array<br>";
	
/* First method to create array. */
$first = array( 1, 2);
		
foreach( $first as $value ) {
	echo "Value is $value <br>";
}
		
/* Second method to create array. */
$first[0] = "one";
$first[1] = "two";
		
foreach( $first as $value ) {
	echo "Value is $value <br>";
}
?>

Output

This is a sample output for your reference shown below:

Created First empty array 
Created second empty array
Value is 1 
Value is 2 
Value is one 
Value is two 

How to Initialize an Array in PHP

We can see another example to execute a task in the below program.

<?php

// Create an empty array
$emptyArray=array();

// Push elements to the array
array_push($emptyArray, "coding", "for", "coders");

// Display array elements
print_r($emptyArray);
?>

Read Also: String Comparison In PHP

Output

Array
(
    [0] => coding
    [1] => for
    [2] => coders
)

Final Thoughts

What we learned through this article is How To Initialize An Array In PHP. Also if you have any doubts please leave a comment via the comment box. And we ask that you benefit everyone who shared this article with your friends.

Leave a Comment