|
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 Pad an Array with the Same Value Multiple Times?
If you want to add the same value multiple times to the end or beginning of an array,
you can use the array_pad($array, $new_size, $value) function. If the second argument, $new_size,
is positive, it will pad to the end of the array. If negative, it will pad
to the beginning of the array. If the absolute value of $new_size if not greater than
the current size of the array, no padding takes place.
Here is a PHP script on how to use array_pad():
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$array = array_pad($array, 6, ">>");
$array = array_pad($array, -8, "---");
print("Padded:\n");
print(join(",", array_values($array)));
print("\n");
?>
This script will print:
Padded:
---,---,PHP,Perl,Java,>>,>>,>>
How To Truncate an Array?
If you want to remove a chunk of values from an array,
you can use the array_splice($array, $offset, $length) function.
$offset defines the starting position of the chunk to be removed.
If $offset is positive, it is counted from the beginning of the array.
If negative, it is counted from the end of the array.
array_splice() also returns the removed chunk of values.
Here is a PHP script on how to use array_splice():
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$removed = array_splice($array, -2, 2);
print("Remaining chunk:\n");
print_r($array);
print("\n");
print("Removed chunk:\n");
print_r($removed);
?>
This script will print:
Remaining chunk:
Array
(
[Zero] => PHP
)
Removed chunk:
Array
(
[One] => Perl
[Two] => Java
)
How To Join Multiple Strings Stored in an Array into a Single String?
If you multiple strings stored in an array, you can join them together into a single string
with a given delimiter by using the implode() function.
Here is a PHP script on how to use implode():
<?php
$date = array('01', '01', '2006');
$keys = array('php', 'string', 'function');
print("A formated date: ".implode("/",$date)."\n");
print("A keyword list: ".implode(", ",$keys)."\n");
?>
This script will print:
A formated date: 01/01/2006
A keyword list: php, string, function
(Continued on next part...)
Part:
1
2
3
4
5
6
7
|