PHP Tutorials: Array functions

I hope you enjoyed reading my last tutorial about PHP: Array. PHP comes with some inbuilt array functions that are very interesting. I am going to tell you some of them because will need them while doing your assignment.

Functions

print_r()

print_r() prints human-readable information about a variable. This function is most commonly used with array to display all the values stored in it.

Syntax: print_r(variable);
<pre>
<?php
	$fruits = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
	print_r ($fruits);
?>
</pre>
OUTPUT: 
<pre>
Array (     
      [a] => apple     
      [b] => banana
      [c] => Array        
        (             
                [0] => x             
                [1] => y             
                [2] => z         
        ) 
)
</pre> 
var_dump()

This function is very similar to print_r() but in addition to the values it also display the information about the value store.

Syntax: var_dump(variable); 
<?php
	$myarray = array(1, 2, array("a", "b", "c"));
	var_dump($myarray);
?>
OUTPUT: 
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
sort()

This function sort an array. Elements will be arranged from lowest to highest.

Syntax: sort(array);
<?php
	$fruits = array("lemon", "orange", "banana", "apple");
	sort($fruits);
	foreach ($fruits as $key => $val) {
	    echo "fruits[" . $key . "] = " . $val . "\n";
	}
?>
OUTPUT: 
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
implode()

Implode function is used to join array elements with a string. You have to provide a glue. A glue is a string or a character which will appear between 2 array elements.

Syntax: implode(glue, array);
<?php

	$array = array('lastname', 'email', 'phone');
	$comma_separated = implode(",", $array);

	echo $comma_separated; // lastname,email,phone

	// Empty string when using an empty array:
	var_dump(implode('hello', array())); // string(0) ""

?>

For more function you can visit Array Functions

Leave a Reply

Your email address will not be published. Required fields are marked *