How To Assigning a New Character in a String?
The string element expression, $string{index}, can also be used at the left side of an assignment statement. This allows you to assign a new character to any position in a string. Here is a PHP script example:
<?php
$string = 'It\'s Friday?';
echo "$string\n";
$string{11} = '!';
echo "$string\n";
?>
This script will print:
It's Friday?
It's Friday!
How to Concatenate Two Strings Together?
You can use the string concatenation operator (.) to join two strings into one. Here is a PHP script example of string concatenation:
<?php
echo 'Hello ' . "world!\n";
?>
This script will print:
Hello world!
How To Compare Two Strings with Comparison Operators?
PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. Those operators use ASCII values of characters from both strings to determine the comparison results. Here is a PHP script on how to use comparison operators:
<?php
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose language.";
if ($a > $b) {
print('$a > $b is true.'."\n");
} else {
print('$a > $b is false.'."\n");
}
if ($a == $b) {
print('$a == $b is true.'."\n");
} else {
print('$a == $b is false.'."\n");
}
if ($a < $b) {
print('$a < $b is true.'."\n");
} else {
print('$a < $b is false.'."\n");
}
?>
This script will print:
$a > $b is true.
$a == $b is false.
$a < $b is false.
How To Convert Numbers to Strings?
In a string context, PHP will automatically convert any numeric value to a string. Here is a PHP script examples:
<?php
print(-1.3e3);
print("\n");
print(strlen(-1.3e3));
print("\n");
print("Price = $" . 99.99 . "\n");
print(1 . " + " . 2 . " = " . 1+2 . "\n");
print(1 . " + " . 2 . " = " . (1+2) . "\n");
print(1 . " + " . 2 . " = 3\n");
print("\n");
?>
This script will print:
-1300
5
Price = $99.99
3
1 + 2 = 3
1 + 2 = 3
The print() function requires a string, so numeric value -1.3e3 is automatically converted to a string "-1300". The concatenation operator (.) also requires a string, so numeric value 99.99 is automatically converted to a string "99.99". Expression (1 . " + " . 2 . " = " . 1+2 . "\n") is a little bit interesting. The result is "3\n" because concatenation operations and addition operation are carried out from left to right. So when the addition operation is reached, we have "1 + 2 = 1"+2, which will cause the string to be converted to a value 1.
How To Convert Strings to Numbers?
In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules:
- The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
- If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise, it will be converted to an integer.
Here is a PHP script example of converting some examples:
<?php
$foo = 1 + "10.5";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "10 Small Pigs";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 4 + "10.2 Little Piggies";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1.0;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
?>
This script will print:
$foo=11.5; type is double
$foo=-1299; type is double
$foo=1; type is integer
$foo=1; type is integer
$foo=11; type is integer
$foo=14.2; type is double
$foo=11; type is double
$foo=11; type is double
How To Get the Number of Characters in a String?
You can use the "strlen()" function to get the number of characters in a string. Here is a PHP script example of strlen():
<?php
print(strlen('It\'s Friday!'));
?>
This script will print:
12
How To Remove White Spaces from the Beginning and/or the End of a String?
There are 4 PHP functions you can use remove white space characters from the beginning and/or the end of a string:
- trim() - Remove white space characters from the beginning and the end of a string.
- ltrim() - Remove white space characters from the beginning of a string.
- rtrim() - Remove white space characters from the end of a string.
- chop() - Same as rtrim().
White space characters are defined as:
- " " (ASCII 32 (0x20)), an ordinary space.
- "\t" (ASCII 9 (0x09)), a tab.
- "\n" (ASCII 10 (0x0A)), a new line (line feed).
- "\r" (ASCII 13 (0x0D)), a carriage return.
- "\0" (ASCII 0 (0x00)), the NULL-byte.
- "\x0B" (ASCII 11 (0x0B)), a vertical tab.
Here is a PHP script example of trimming strings:
<?php
$text = "\t \t Hello world!\t \t ";
$leftTrimmed = ltrim($text);
$rightTrimmed = rtrim($text);
$bothTrimmed = trim($text);
print("leftTrimmed = ($leftTrimmed)\n");
print("rightTrimmed = ($rightTrimmed)\n");
print("bothTrimmed = ($bothTrimmed)\n");
?>
This script will print:
leftTrimmed = (Hello world! )
rightTrimmed = ( Hello world!)
bothTrimmed = (Hello world!)
How To Remove the New Line Character from the End of a Text Line?
If you are using fgets() to read a line from a text file, you may want to use the chop() function to remove the new line character from the end of the line as shown in this PHP script:
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while ($line=fgets()) {
$line = chop($line);
# process $line here...
}
fclose($handle);
?>
How To Remove Leading and Trailing Spaces from User Input Values?
If you are taking input values from users with a Web form, users may enter extra spaces at the beginning and/or the end of the input values. You should always use the trim() function to remove those extra spaces as shown in this PHP script:
<?php
$name = $_REQUEST("name");
$name = trim($name);
# $name is ready to be used...
?>
How to Find a Substring from a Given String?
To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():
<?php
$haystack1 = "2349534134345pickzycenter16504381640386488129";
$haystack2 = "pickzycenter234953413434516504381640386488129";
$haystack3 = "center234953413434516504381640386488129pickzy";
$pos1 = strpos($haystack1, "pickzycenter");
$pos2 = strpos($haystack2, "pickzycenter");
$pos3 = strpos($haystack3, "pickzycenter");
print("pos1 = ($pos1); type is " . gettype($pos1) . "\n");
print("pos2 = ($pos2); type is " . gettype($pos2) . "\n");
print("pos3 = ($pos3); type is " . gettype($pos3) . "\n");
?>
This script will print:
pos1 = (13); type is integer
pos2 = (0); type is integer
pos3 = (); type is boolean
"pos3" shows strpos() can return a Boolean value.
What Is the Best Way to Test the strpos() Return Value?
Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the "Identical(===)" operator. Do not use the "Equal(==)" operator, because it does not differentiate "0" and "false". Check out this PHP script on how to use strpos():
<?php
$haystack = "needle234953413434516504381640386488129";
$pos = strpos($haystack, "needle");
if ($pos==false) {
print("Not found based (==) test\n");
} else {
print("Found based (==) test\n");
}
if ($pos===false) {
print("Not found based (===) test\n");
} else {
print("Found based (===) test\n");
}
?>
This script will print:
Not found based (==) test
Found based (===) test
Of course, (===) test is correct.
How To Take a Substring from a Given String?
If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():
<?php
$string = "beginning";
print("Position counted from left: ".substr($string,0,5)."\n");
print("Position counted form right: ".substr($string,-7,3)."\n");
?>
This script will print:
Position counted from left: begin
Position counted form right: gin
substr() can take negative starting position counted from the end of the string.
How To Replace a Substring in a Given String?
If you know the position of a substring in a given string, you can replace that substring by another string by using the substr_replace() function. Here is a PHP script on how to use substr_replace():
<?php
$string = "Warning: System will shutdown in NN minutes!";
$pos = strpos($string, "NN");
print(substr_replace($string, "15", $pos, 2)."\n");
sleep(10*60);
print(substr_replace($string, "5", $pos, 2)."\n");
?>
This script will print:
Warning: System will shutdown in 15 minutes!
(10 minutes later)
Warning: System will shutdown in 5 minutes!
Like substr(), substr_replace() can take negative starting position counted from the end of the string.
How To Reformat a Paragraph of Text?
You can wordwrap() reformat a paragraph of text by wrapping lines with a fixed length. Here is a PHP script on how to use wordwrap():
<?php
$string = "TRADING ON MARGIN POSES ADDITIONAL
RISKS AND IS NOT SUITABLE FOR ALL
INVESTORS.
A COMPLETE LIST OF THE RISKS ASSOCIATED WITH MARGIN TRADING IS
AVAILABLE IN THE MARGIN RISK DISCLOSURE DOCUMENT.";
$string = str_replace("\n", " ", $string);
$string = str_replace("\r", " ", $string);
print(wordwrap($string, 40)."\n");
?>
This script will print:
TRADING ON MARGIN POSES ADDITIONAL
RISKS AND IS NOT SUITABLE FOR ALL
INVESTORS. A COMPLETE LIST OF THE
RISKS ASSOCIATED WITH MARGIN TRADING IS
AVAILABLE IN THE MARGIN RISK DISCLOSURE
DOCUMENT.
The result is not really good because of the extra space characters. You need to learn preg_replace() to replace them with a single space character.
How To Convert Strings to Upper or Lower Cases?
Converting strings to upper or lower cases are easy. Just use strtoupper() or strtolower() functions. Here is a PHP script on how to use them:
<?php
$string = "PHP string functions are easy to use.";
$lower = strtolower($string);
$upper = strtoupper($string);
print("$lower\n");
print("$upper\n");
print("\n");
?>
This script will print:
php string functions are easy to use.
PHP STRING FUNCTIONS ARE EASY TO USE.
How To Convert the First Character to Upper Case?
If you are processing an article, you may want to capitalize the first character of a sentence by using the ucfirst() function. You may also want to capitalize the first character of every words for the article title by using the ucwords() function. Here is a PHP script on how to use ucfirst() and ucwords():
<?php
$string = "php string functions are easy to use.";
$sentence = ucfirst($string);
$title = ucwords($string);
print("$sentence\n");
print("$title\n");
print("\n");
?>
This script will print:
Php string functions are easy to use.
Php String Functions Are Easy To Use.
How To Compare Two Strings with strcmp()?
PHP supports 3 string comparison operators, <, ==, and >, that generates Boolean values. But if you want to get an integer result by comparing two strings, you can the strcmp() function, which compares two strings based on ASCII values of their characters. Here is a PHP script on how to use strcmp():
<?php
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose language.";
print('strcmp($a, $b): '.strcmp($a, $b)."\n");
print('strcmp($b, $a): '.strcmp($b, $a)."\n");
print('strcmp($a, $a): '.strcmp($a, $a)."\n");
?>
This script will print:
strcmp($a, $b): 1
strcmp($b, $a): -1
strcmp($a, $a): 0
As you can see, strcmp() returns 3 possible values:
- 1: The first string is greater than the section string.
- -1: The first string is less than the section string.
- 0: The first string is equal to the section string.
How To Convert Strings in Hex Format?
If you want convert a string into hex format, you can use the bin2hex() function. Here is a PHP script on how to use bin2hex():
<?php
$string = "Hello\tworld!\n";
print($string."\n");
print(bin2hex($string)."\n");
?>
This script will print:
Hello world!
48656c6c6f09776f726c64210a
How To Generate a Character from an ASCII Value?
If you want to generate characters from ASCII values, you can use the chr() function. chr() takes the ASCII value in decimal format and returns the character represented by the ASCII value. chr() complements ord(). Here is a PHP script on how to use chr():
<?php
print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n");
print(ord("H")."\n");
?>
This script will print:
Hello
72
How To Convert a Character to an ASCII Value?
If you want to convert characters to ASCII values, you can use the ord() function, which takes the first charcter of the specified string, and returns its ASCII value in decimal format. ord() complements chr(). Here is a PHP script on how to use ord():
<?php
print(ord("Hello")."\n");
print(chr(72)."\n");
?>
This script will print:
72
H
How To Split a String into Pieces?
There are two functions you can use to split a string into pieces:
- 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 Join Multiple Strings 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
How To Apply UUEncode to a String?
UUEncode (Unix-to-Unix Encoding) is a simple algorithm to convert a string of any characters into a string of printable characters. UUEncode is reversible. The reverse algorithm is called UUDecode. PHP offeres two functions for you to UUEncode or UUDecode a string: convert_uuencode() and convert_uudecode(), Here is a PHP script on how to use them:
<?php
$msgRaw = "
From\tTo\tSubject
Joe\tLee\tHello
Dan\tKia\tGreeting";
$msgEncoded = convert_uuencode($msgRaw);
$msgDecoded = convert_uudecode($msgEncoded);
if ($msgRaw === $msgDecoded) {
print("Conversion OK\n");
print("UUEncoded message:\n");
print("-->$msgEncoded<--\n");
print("UUDecoded message:\n");
print("-->$msgDecoded<--\n");
} else {
print("Conversion not OK:\n");
}
?>
This script will print:
Conversion OK
UUEncoded message:
-->M1G)O;0E4;PE3=6)J96-T#0I*;V4)3&5E"4AE;&QO#0I$86X)2VEA"4=R965T
#:6YG
`
<--
UUDecoded message:
-->
From To Subject
Joe Lee Hello
Dan Kia Greeting<--
The output shows you that the UUEncode string is a multiple-line string with a special end-of-string mark \x20.
How To Replace a Group of Characters by Another Group?
While processing a string, you may want to replace a group of special characters with some other characters. For example, if you don't want to show user's email addresses in the original format to stop email spammer collecting real email addresses, you can replace the "@" and "." with something else. PHP offers the strtr() function with two format to help you:
- strtr(string, from, to) - Replacing each character in "from" with the corresponding character in "to".
- strtr(string, map) - Replacing each substring in "map" with the corresponding substring in "map".
Here is a PHP script on how to use strtr():
<?php
$email = "joe@dev.pickzycenter.moc";
$map = array("@" => " at ", "." => " dot ");
print("Original: $email\n");
print("Character replacement: ".strtr($email, "@.", "#_")."\n");
print("Substring replacement: ".strtr($email, $map)."\n");
?>
This script will print:
Original: joe@dev.pickzycenter.moc
Character replacement: joe#dev_pickzycenter_moc
Substring replacement: joe at dev dot pickzycenter dot moc
To help you to remember the function name, strtr(), "tr" stands for "translation".
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:
How To Retrieve Values out of an Array?
You can retrieve values out of arrays using the array element expression $array[$key]. Here is a PHP example script:
<?php $languages = array(); $languages["Zero"] = "PHP"; $languages["One"] = "Perl"; $languages["Two"] = "Java"; print("Array with inserted values:\n"); print_r($languages); ?>
This script will print:
Array with default keys:
The second value: Perl
Array with specified keys:
The third value: Java
What Types of Data Can Be Used as Array Keys?
Two types of data can be used as array keys: string and integer. When a string is used as a key and the string represent an integer, PHP will convert the string into a integer and use it as the key. Here is a PHP script on different types of keys:
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
print("Array with mixed keys:\n");
print_r($mixed);
print("\$mixed[3] = ".$mixed[3]."\n");
print("\$mixed[\"3\"] = ".$mixed["3"]."\n");
print("\$mixed[\"\"] = ".$mixed[""]."\n");
?>
This script will print:
Array with mixed keys:
Array
(
[Zero] => PHP
[1] => Perl
[Two] => Java
[3] => C+
[] => Basic
)
$mixed[3] = C+
$mixed["3"] = C+
$mixed[""] = Basic
Note that an empty string can also be used as a key.
How Values in Arrays Are Indexed?
Values in an array are all indexed their corresponding keys. Because we can use either an integer or a string as a key in an array, we can divide arrays into 3 categories:
- Numerical Array - All keys are sequential integers.
- Associative Array - All keys are strings.
- Mixed Array - Some keys are integers, some keys are strings.
Can You Add Values to an Array without a Key?
Can You Add Values to an Array with a Key? The answer is yes and no. The answer is yes, because you can add values without specipickzyng any keys. The answer is no, because PHP will add a default integer key for you if you are not specipickzyng a key. PHP follows these rules to assign you the default keys:
- Assign 0 as the default key, if there is no integer key exists in the array.
- Assign the highest integer key plus 1 as the default key, if there are integer keys exist in the array.
Here is a PHP example script:
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
print("Array with default keys:\n");
print_r($mixed);
?>
This script will print:
Array with default keys:
Array
(
[Zero] => PHP
[1] => Perl
[Two] => Java
[3] => C+
[] => Basic
[4] => Pascal
[5] => FORTRAN
)
Can You Copy an Array?
You can create a new array by copying an existing array using the assignment statement. Note that the new array is not a reference to the old array. If you want a reference variable pointing to the old array, you can use the reference operator "&". Here is a PHP script on how to copy an array:
<?php
$oldArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$newArray = $oldArray;
$refArray = &$oldArray;
$newArray["One"] = "Python";
$refArray["Two"] = "C#";
print("\$newArray[\"One\"] = ".$newArray["One"]."\n");
print("\$oldArray[\"One\"] = ".$oldArray["One"]."\n");
print("\$refArray[\"Two\"] = ".$refArray["Two"]."\n");
print("\$oldArray[\"Two\"] = ".$oldArray["Two"]."\n");
?>
This script will print:
$newArray["One"] = Python
$oldArray["One"] = Perl
$refArray["Two"] = C#
$oldArray["Two"] = C#
How to Loop through an Array?
The best way to loop through an array is to use the "foreach" statement. There are two forms of "foreach" statements:
- foreach ($array as $value) {} - This gives you only one temporary variable to hold the current value in the array.
- foreach ($array as $key=>$value) {} - This gives you two temporary variables to hold the current key and value in the array.
Here is a PHP script on how to use "foreach" on an array:
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$array["3"] = "C+";
$array[""] = "Basic";
$array[] = "Pascal";
$array[] = "FORTRAN";
print("Loop on value only:\n");
foreach ($array as $value) {
print("$value, ");
}
print("\n\n");
print("Loop on key and value:\n");
foreach ($array as $key=>$value) {
print("[$key] => $value\n");
}
?>
This script will print:
Loop on value only:
PHP, Perl, Java, C+, Basic, Pascal, FORTRAN,
Loop on key and value:
[Zero] => PHP
[One] => Perl
[Two] => Java
[3] => C+
[] => Basic
[4] => Pascal
[5] => FORTRAN
How the Values Are Ordered in an Array?
PHP says that an array is an ordered map. But how the values are ordered in an array? The answer is simple. Values are stored in the same order as they are inserted like a queue. If you want to reorder them differently, you need to use a sort function. Here is a PHP script show you the order of array values:
<?php
$mixed = array();
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$mixed["Two"] = "";
unset($mixed[4]);
print("Order of array values:\n");
print_r($mixed);
?>
This script will print:
Order of array values:
Array
(
[Two] =>
[3] => C+
[Zero] => PHP
[1] => Perl
[] => Basic
[5] => FORTRAN
)
How To Copy Array Values to a List of Variables?
If you want copy all values of an array to a list of variable, you can use the list() construct on the left side of an assignment operator. list() will only take values with integer keys starting from 0. Here is a PHP script on how to use list() construct:
<?php
$array = array("Google", "Yahoo", "Netscape");
list($first, $second, $third) = $array;
print("Test 1: The third site = $third\n");
list($month, $date, $year) = split("/","1/1/2006");
print("Test 2: Year = $year\n");
$array = array("Zero"=>"PHP", 1=>"Basic", "One"=>"Perl",
0=>"Pascal", 2=>"FORTRAN", "Two"=>"Java");
list($first, $second, $third) = $array;
print("Test 3: The third language = $third\n");
?>
This script will print:
Test 1: The third site = Netscape
Test 2: Year = 2006
Test 3: The third language = FORTRAN
Test 2 uses the array returned by the split() function. Test 3 shows that list() will ignore any values with string keys.
How To Get the Total Number of Values in an Array?
You can get the total number of values in an array by using the count() function. Here is a PHP example script:
<?php
$array = array("PHP", "Perl", "Java");
print_r("Size 1: ".count($array)."\n");
$array = array();
print_r("Size 2: ".count($array)."\n");
?>
This script will print:
Size 1: 3
Size 2: 0
Note that count() has an alias called sizeof().
How Do You If a Key Is Defined in an Array?
There are two functions can be used to test if a key is defined in an array or not:
- array_key_exists($key, $array) - Returns true if the $key is defined in $array.
- isset($array[$key]) - Returns true if the $key is defined in $array.
Here is a PHP example script:
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Is 'One' defined? ".array_key_exists("One", $array)."\n");
print("Is '1' defined? ".array_key_exists("1", $array)."\n");
print("Is 'Two' defined? ".isset($array["Two"])."\n");
print("Is '2' defined? ".isset($array[2])."\n");
?>
This script will print:
Is 'One' defined? 1
Is '1' defined?
Is 'Two' defined? 1
Is '2' defined?
How To Find a Specific Value in an Array?
There are two functions can be used to test if a value is defined in an array or not:
- array_search($value, $array) - Returns the first key of the matching value in the array, if found. Otherwise, it returns false.
- in_array($value, $array) - Returns true if the $value is defined in $array.
Here is a PHP script on how to use arrary_search():
<?php
$array = array("Perl", "PHP", "Java", "PHP");
print("Search 1: ".array_search("PHP",$array)."\n");
print("Search 2: ".array_search("Perl",$array)."\n");
print("Search 3: ".array_search("C#",$array)."\n");
print("\n");
?>
This script will print:
Search 1: 1
Search 2: 0
Search 3:
How To Get All the Keys Out of an Array?
Function array_keys() returns a new array that contains all the keys of a given array. Here is a PHP script on how to use array_keys():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$keys = array_keys($mixed);
print("Keys of the input array:\n");
print_r($keys);
?>
This script will print:
Keys of the input array:
Array
(
[0] => Zero
[1] => 1
[2] => Two
[3] => 3
[4] =>
[5] => 4
[6] => 5
How To Get All the Values Out of an Array?
F unction array_values() returns a new array that contains all the keys of a given array. Here is a PHP script on how to use array_values():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$values = array_values($mixed);
print("Values of the input array:\n");
print_r($values);
?>
This script will print:
Values of the input array:
Array
(
[0] => PHP
[1] => Perl
[2] => Java
[3] => C+
[4] => Basic
[5] => Pascal
[6] => FORTRAN
)
How To Sort an Array by Keys?
Sorting an array by keys can be done by using the ksort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the keys. Here is a PHP script on how to use ksort():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
ksort($mixed);
print("Sorted by keys:\n");
print_r($mixed);
?>
This script will print:
Sorted by keys:
Array
(
[] => Basic
[Two] => Java
[Zero] => PHP
[1] => Perl
[3] => C+
[4] => Pascal
[5] => FORTRAN
)
How To Sort an Array by Values?
Sorting an array by values is doable by using the sort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the values. Then it will replace all keys with integer keys sequentially starting with 0. So using sort() on arrays with integer keys (traditional index based array) is safe. It is un-safe to use sort() on arrays with string keys (maps). Be careful. Here is a PHP script on how to use sort():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
sort($mixed);
print("Sorted by values:\n");
print_r($mixed);
?>
This script will print:
Sorted by values:
Array
(
[0] => Basic
[1] => C+
[2] => FORTRAN
[3] => Java
[4] => PHP
[5] => Pascal
[6] => Perl
)
|
0 comments:
Have any question? Feel Free To Post Below: