PHP array() Function with Example

PHP array() Function: Here, we will find out about the array() work with the example in PHP.

PHP array() Function

array() work is a predefined work in PHP, it is utilized to make an array of the components, array of the arrays and so forth.

By utilizing array() work, we can make two kinds of arrays,

  • Recorded arrays
  • Cooperative (arrays with the keys and values)
  • What’s more, multidimensional arrays

Syntax to make a recorded array:

    array(element1, element2, element2, ...);

Create an array with keys:

    array(key1=>value1, key2=>value2, key3=>value3, ...);

PHP Code:

Here, we are making a recorded array and printing the array with individually component (utilizing files) and furthermore printing the total array.

<?php
	//array of numbers
	$arr_num = array(10, 20, 30, 40, 50);
	//array with strings
	$arr_string = array("Laptop", "Mobile", "Tablet");
	//array with mixed types
	$arr_mixed = array("Hello", 10, "friends", 20);
	
	//printing arrays elements
	print ("Array elements: $arr_num[0], $arr_num[1],  $arr_num[2],  $arr_num[3],  $arr_num[4]\n");
	print ("Array elements: $arr_string[0], $arr_string[1],  $arr_string[2]\n");
	print ("Array elements: $arr_mixed[0], $arr_mixed[1],  $arr_mixed[2],   $arr_mixed[3]\n");	
	
	//printing complete arrays
	print ("arr_num is...\n");
	print_r ($arr_num);
	print ("arr_string is...\n");
	print_r ($arr_string);
	print ("arr_mixed is...\n");
	print_r ($arr_mixed);
?>

Output:

Array elements: 10, 20,  30,  40,  50
Array elements: Laptop, Mobile,  Tablet
Array elements: Hello, 10,  friends,   20
arr_num is...
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
arr_string is...
Array
(
    [0] => Laptop
    [1] => Mobile
    [2] => Tablet
)
arr_mixed is...
Array
(
    [0] => Hello
    [1] => 10
    [2] => friends
    [3] => 20
)

PHP Code:

<?php
	//creating student array with keys & values
	$std = array('id' => "101", 'name' => "Amit", 'course' => "B.Tech");

	//printing elemenets
	print ("std elements...\n");
	print ("Id = " . $std['id'] . " Name = " . $std['name'] . " Course = " . $std['course']);
	
	//printing complete array
	print ("std...\n");
	print_r($std);
?>

Output:

std elements...
Id = 101 Name = Amit Course = B.Techstd...
Array
(
    [id] => 101
    [name] => Amit
    [course] => B.Tech
)

Here, we are making cooperative (array with keys and values) and printing components utilizing keys and furthermore printing the total array.

Leave a Comment

error: Alert: Content is protected!!