PHP Array Example



PHP Array Contruct Example.
<?php
	$zoo = array('Monkey', 'Zebra', 'Lion', 'Tiger', 'Elephant');
    echo $zoo[0].'br>';
    echo $zoo[1].'br>';
    echo $zoo[2].'br>';
    echo $zoo[3].'br>';
    echo $zoo[4].'br>';
?>
Get datatype of Array.
<?php
	$zoo = array('Monkey', 'Zebra', 'Lion', 'Tiger', 'Elephant');
    var_dump($zoo);
?>
Array indices
<?php
	$basket = array('red'=>'Rose', 'yellow' =>'Sunflower', 'pink' => 'Lotus', 'white' => 'Lily');
	echo $basket['red'].'br>';
    echo $basket['yellow'].'br>';
    echo $basket['pink'].'br>';
    echo $basket['white'].'br>';
?>
Multidimensional Array Example
<?php
	$combo = array('fruit' =>
					array('red' => 'Mango',
						  'orange' => 'Orange',
						  'green' => 'Graphs',
						  'yellow' => 'banana')
					'flower' =>
					array('red' => 'Rose',
						  'yellow' => 'Sunflower',
						  'pink' => 'Lotus',
						  'white' => 'Lily')
			    );
				
	echo 'The red flower is '.$combo['flower']['red'];		
	echo '<br/>';
	echo 'The red fruit is '.$combo['fruit']['red'];		
?>
Array Iteration Example
<?php
	$zoo = array('Monkey', 'Zebra', 'Lion', 'Tiger', 'Elephant');
	forreach($zoo as $animal){
		echo $animal.'<br/>';
    }	
?>
Array Iteration Example2
<?php
	$combo = array('fruit' =>
					array('red' => 'Mango',
						  'orange' => 'Orange',
						  'green' => 'Graphs',
						  'yello' => 'banana')
					'flower' =>
					array('red' => 'Rose',
						  'yellow' => 'Sunflower',
						  'pink' => 'Lotus',
						  'white' => 'Lily')
			    );
	forreach($combo as $subcombo=>$data){
		foreach($data as $key=>$value) {
		echo 'The '.$key. $subcombo. 'is '.$value.'<br/>';
		}
    }	
?>
Delete from Arrays
<?php
	$basket = array('red'=>'Rose', 'yellow' =>'Sunflower', 'pink' => 'Lotus', 'white' => 'Lily');
	unset($basket['red']);
	unset($basket['pink']);
	echo '<pre>'; print_r($basket);
?>
Merge Two Arrays
<?php
	$a = array('10', '3', '3', '2');
	$b = array('34', '54', '2', '40');
    $c = array_merge($a, $b);
	echo '<pre>'; print_r($c);
?>
Get Array Difference
<?php
	$a = array('10', '3', '3', '2');
	$b = array('10', '2', '5', '4');
    $c = array_diff($a, $b);
	echo '<pre>'; print_r($c);
?>
Get unique values from an Array
<?php
	$a = array('12', '11', '12', '02', '44', '2');
    $c = array_unique($a);
	echo '<pre>'; print_r($c);
?>
Example to check wether an argument is an array or not
<?php
	$a = array('12', '11', '12', '02', '44', '2');
	$b = 12;
    echo is_array($a);
	echo '<br/>';
	echo is_array($b);
?>
Example to get size of an Array
<?php
	$basket = array('red'=>'Rose', 'yellow' =>'Sunflower', 'pink' => 'Lotus', 'white' => 'Lily');
    echo count($basket);
?>


Read more articles


General Knowledge



Learn Popular Language