PHP array

Image
  An array stores multiple values in one single variable. In PHP, the array() function is used to create an array. Example: <?php $pets = array ( "dog" , "cat" , "rabbit" ); echo $pets [ 0 ] . "," . $pets [ 1 ] . "," . $pets [ 2 ]; ?> Output: dog,cat,rabbit An array is a special variable, which can hold more than one value at a time. If you have a list of student names, storing the names in single variables could like this, $name1 = "Peter" $name2 = "Mickle" $name2 = "Bravo" However, what if you want to loop through the names and find a specific one? And what if you had 3 names, but 1000? The solution is to create an array . An array can hold many values under a single name, and you can access the values by referring to an index number. There are three different kind of arrays. Numeric array – Arrays with a numeric index Associative array – Arrays with named keys

PHP explode function

PHP explode function

In this post, you’ll learn how to use the PHP explode() function.

PHP explode() function returns an array of strings by splitting a string by a separator. The following shows the syntax of the PHP explode() function.

Syntax:
	explode(separator, string, limit)
  • separator - Required. Specifies where to break the string
  • string – Required. The string to split
  • limit – Optional. Specifies the number of array elements to return
    Possible Values
    • Greater than 0 - Returns an array with a maximum of limit element(s)
    • Less than 0 - Returns an array except for the last -limit element(s)
    • 0 - Returns an array with one element
Example:
<?php 
$txt = "Welcome to PHP Coding Help.";
print_r (explode(" ",$txt));
?>
Output:

Array ( [0] => Welcome [1] => to [2] => PHP [3] => Coding [4] => Help. )

Using the limit parameter to return a number of array elements:

Example:
<?php 
$str = 'red,blue,yellow,green';

// zero limit
print_r(explode(',',$str,0));
print "<br>";

// positive limit
print_r(explode(',',$str,2));
print "<br>";

// negative limit 
print_r(explode(',',$str,-1));
?>
Output:

Array ( [0] => red,blue,yellow,green )
Array ( [0] => red [1] => blue,yellow,green )
Array ( [0] => red [1] => blue [2] => yellow )

Comments

Popular posts from this blog

PHP Code for get Client IP Address

PHP Script for MySqli Database Connection