|
Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index
PHP Script Tips - Understanding PHP Arrays and Their Basic Operations
By: FYICenter.com
Part:
1
2
3
4
A collection of 11 tips on PHP array introduction. Clear answers are provided with tutorial exercises on declaring and creating arrays, assigning and retrieving array elements, identifying elements by keys and indexes, copying arrays.
Topics included in this collection are:
- What Is an Array in PHP?
- How To Create an Array?
- How To Test If a Variable Is an Array?
- How To Retrieve Values out of an Array?
- What Types of Data Can Be Used as Array Keys?
- How Values in Arrays Are Indexed?
- Can You Add Values to an Array without a Key?
- Can You Copy an Array?
- How to Loop through an Array?
- How the Values Are Ordered in an Array?
- How To Copy Array Values to a List of Variables?
What Is an Array in PHP?
An array in PHP is really an ordered map of pairs of keys and values.
Comparing with Perl, an array in PHP is not like a normal array in Perl. An array in PHP is like
an associate array in Perl. But an array in PHP can work like a normal array in Perl.
Comparing with Java, an array in PHP is not like an array in Java. An array in PHP is like
a TreeMap class in Java. But an array in PHP can work like an array in Java.
How To Create an Array?
You can create an array using the array() constructor. When calling array(),
you can also initialize the array with pairs of keys and values.
Here is a PHP script on how to use array():
<?php
print("Empty array:\n");
$emptyArray = array();
print_r($emptyArray);
print("\n");
print("Array with default keys:\n");
$indexedArray = array("PHP", "Perl", "Java");
print_r($indexedArray);
print("\n");
print("Array with specified keys:\n");
$mappedArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print_r($mappedArray);
print("\n");
?>
This script will print:
Empty array:
Array
(
)
Array with default keys:
Array
(
[0] => PHP
[1] => Perl
[2] => Java
)
Array with specified keys:
Array
(
[Zero] => PHP
[One] => Perl
[Two] => Java
)
How To Test If a Variable Is an Array?
Testing if a variable is an array is easy. Just use the is_array() function.
Here is a PHP script on how to use is_array():
<?php
$var = array(0,0,7);
print("Test 1: ". is_array($var)."\n");
$var = array();
print("Test 2: ". is_array($var)."\n");
$var = 1800;
print("Test 3: ". is_array($var)."\n");
$var = true;
print("Test 4: ". is_array($var)."\n");
$var = null;
print("Test 5: ". is_array($var)."\n");
$var = "PHP";
print("Test 6: ". is_array($var)."\n");
print("\n");
?>
This script will print:
Test 1: 1
Test 2: 1
Test 3:
Test 4:
Test 5:
Test 6:
(Continued on next part...)
Part:
1
2
3
4
|