|
Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index
PHP Script Tips - PHP Built-in Functions for Arrays
By: FYICenter.com
Part:
1
2
3
4
5
6
7
(Continued from previous part...)
How To Split a String into an Array of Substring?
There are two functions you can use to split a string into an Array of Substring:
- explode(substring, string) - Splitting a string based on a substring. Faster than split().
- split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.
Both functions will use the given criteria, substring or pattern, to find the splitting points in the string,
break the string into pieces at the splitting points, and return the pieces in an array.
Here is a PHP script on how to use explode() and split():
<?php
$list = explode("_","php_strting_function.html");
print("explode() returns:\n");
print_r($list);
$list = split("[_.]","php_strting_function.html");
print("split() returns:\n");
print_r($list);
?>
This script will print:
explode() returns:
Array
(
[0] => php
[1] => strting
[2] => function.html
)
split() returns:
Array
(
[0] => php
[1] => strting
[2] => function
[3] => html
)
The output shows you the power of power of split() with a regular expression pattern as the splitting criteria.
Pattern "[_.]" tells split() to split whenever there is a "_" or ".".
How To Get the Minimum or Maximum Value of an Array?
If you want to get the minimum or maximum value of an array,
you can use the min() or max() function.
Here is a PHP script on how to use min() and max():
<?php
$array = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Minimum number: ".min($array)."\n");
print("Maximum number: ".max($array)."\n");
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Minimum string: ".min($array)."\n");
print("Maximum string: ".max($array)."\n");
?>
This script will print:
Minimum number: 1
Maximum number: 7
Minimum string: Java
Maximum string: Perl
As you can see, min() and max() work for string values too.
Part:
1
2
3
4
5
6
7
|