PHP: Arrays
BigBob98
Remove all numeric key index from array changing array in place:
<?php
) {
foreach () {
if ()) {
unset(]);
}
}
}
?>
php_net at mcdragonsoftware dot com
If you're like me you've needed to use index paths (an array as the index for a multi-dimensional array) and dearly hoped that PHP had native support for it; probably even tried something like:
<?php
$TEST = array(
array( ),
array( ),
array( ),
);
);
echo ];
?>
only to receive the Warning: "Illegal offset type...".
I spent the last 3 hours solving that problem, here is my 11 function solution: (these functions have been tested/verified in PHP 5.3, but not yet in PHP 4)
<?php
//// mda = Multi-Dimensional Array
) {
;
foreach( (array)) {
];
}
return $SUB;
}
function ) {
;
foreach( (array)) {
];
}
;
return $ARRAY;
}
function ) {
;
foreach( (array)) {
];
}
);
return $ARRAY;
}
function ) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
unset(]);
} else {
];
}
}
return $ARRAY;
}
//// mdi = Multi-Dimensional Index (for use with mda)
) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
);
];
} else {
];
}
}
return $PATH;
}
function ) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
);
);
];
} else {
];
}
}
return $PATH;
}
function ) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
);
);
];
} else {
];
}
}
return $PATH;
}
function ) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
);
];
} else {
];
}
}
return $PATH;
}
function ) {
unset(]);
return $PATH;
}
function ) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
];
);
];
} else {
];
}
}
return $PATH;
}
function ) {
;
;
foreach( (array)) {
$i++;
if( ) ) {
];
);
];
} else {
];
}
}
return $PATH;
}
$TEST = array(
array( ),
array( ),
array( ),
);
);
);
);
) );
));
// $TEST = mcds_mda_get($TEST, $INDEX);
) );
echo ;
?>
martijntje at martijnotto dot nl
Please note that adding the magic __toString() method to your objects will not allow you to seek an array with it, it still throws an Illegal Offset warning.
The solution is to cast it to a string first, like this
$array[(string) $stringableObject]
Alex Galletti
On 5.4 I would also assume that the shortened array syntax would be usable to define an array:
<?php
$myArray = []; // instead of array();
?>
Nothing major but it could be of convenience.
Anonymous
Here's an easier way to access associative array values by their numeric index:
<?php
//sample associative array:
);
);
echo // => apple
// => banana
// => carrot
// => dragon fruit
?>
Anonymous
This is a simple solution for taking previous and next items, even if we are at the ends of the array.
<?php
$current_key; // the key of the item we want to search from
])) {
// get the next item if there is
} else {
// if not take the first (this means this is the end of the array)
}
if (isset(])) {
// get the previous item if there is
} else {
// if not take the last item (this means this is the beginning of the array)
}
?>
prince at 3ddatalabs dot com
Hi, you also can try goAssocArrayNumeric() on two-dimensional or three-dimensional arrays.
<?php
//Now it's a two-dimensional array
));
echo //won't work! But,
//using the same function used to access associative arrays numerically, we may access 2-dimensional arrays numerically.
)
{
;
foreach ()
{
$i++;
if()
{
return $v;
}
}
return FALSE;
}
//usage: applying it twice.
//apple
//coco
//coffee
?>
Thanks!
Prince.
prince at 3ddatalabs dot com
Hi, here's a way to access an associative array via it's numeric index.
<?php
//sample associative array:
);
echo ];
//Above won't work! Because you can't access an associative array numerically. But,
)
{
;
foreach ()
{
$i++;
if ()
{
return $v;
}
}
return FALSE;
}
//usage:
//apple
//dragon fruit
?>
Hope it helps!
Thanks.
Zane MegaLab.it
Beware: you can't access an associative array via it's numeric index:
<?php
$a = array(
,
,
'safafsa' => 'hfdhfdf'
);
echo // Undefined index, not 'bar'
?>
mlvljr
please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php).
abimaelrc
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
){
;
){
);
});
return $val;
}
$arr = array(
,
'bar' => array(
,
,
'vegetable' => array(
,
)
),
,
);
// string(6) "carrot"
// bool(false)
// string(3) "baz"
// string(5) "candy"
// bool(false)
?>
chris AT cmbuckley DOT co DOT uk
Possibly unexpected behaviour:
<?php
$array = array();
// E_NOTICE (undefined key)
;
// no E_NOTICE
?>
Ganpat Thakur
I was in need to get value of key which resides at any level in an multidimensional array. Unfortunately there is no such array function. So I write my own as below...
<?php
) {
if ()) {
foreach () {
if () {
return $v;
}
elseif ()) {
return );
}
}
}
return FALSE;
}
?>
Hope this will help to few.
anhsang9x at gmail dot com
I'm want to save values in array and display its, can to simple way:
<?php
$arr1 = array();//begin array
//array's index
$value_return = array();//Values me need
++)
{
//use to be function random for get values from 10 to 100.
//Get values me need.
{
//save values in this array
//get space save for index.
}
}
//display result.
)
echo ;
);
?>
lemurjan at gmail dot com
Sometimes you may need an array of constants including concatenated strings.
That works fine in this case:
<?php
define);
function ) {
;
foreach (; };
return $r;
}
// DECLARING ARRAY (1)
);
echo );
?>
This seems rather strange behavior in a CLASS nevertheless:
<?php
class wrong_class {
// DECLARING ARRAY (2)
);
function __toString() {
return );
}
}
();
echo $wc;
/*
Parse error: parse error, expecting `')'' in ... code on line 21
*/
?>
Anyway, if you force this declaring method inside a CLASS, you could change the object map directly:
<?php
class proper_class {
function __construct() {
// DECLARING ARRAY (3)
);
}
function __toString() {
return );
}
}
();
echo $pc;
?>
falkon303 at gmail dot com
Multidimensional arrays work great for checking search options if they exist in a $_GET string. The following saved me a lot of time.
<?php
$advanced_option);
);
);
foreach(])
{
// HERE WARE ARE GOING INTO EACH ARRAY'S VALUES/ITEMS
];
foreach(])
{
// IF THE SEARCH OPTI0N EXISTS IN THE GET STRING, SET AN ARRAY NAMED AFTER THAT VALUE TO BE CHECKED (FOR CHECKBOXES & RADIOBUTTONS)
])
{
;
}
}
}
?>
Anonymous
In case you had to get an element from a function-returned array without having to save the array to a variable, here's a workaround I've come up with.
<?php
$stuff = 'something random here';
// To get the first element in the array, use reset
));
// Returns "something"
// To get the last element, use end
));
// Returns "here"
// For an in-between element, you can use array_search on the flipped array
//key for the element
)));
// Returns "random"
?>
Flappi282
Heres a simple function I wrote to remove a value from an array, without leaving a hole:
<?php
){
foreach(){
if(){
]));
return true;
break;
}
}
?>
Returns true on success, or false on failure. The array will be automatically updated
Walter Tross
It is true that "array assignment always involves value copying", but the copy is a "lazy copy". This means that the data of the two variables occupy the same memory as long as no array element changes.
E.g., if you have to pass an array to a function that only needs to read it, there is no advantage at all in passing it by reference.
ivegner at yandex dot ru
Like in Perl, you can use curly braces ({}) instead of square brackets ([]) to access array members:
<?php
$a = array ();
;
;
print ];
?>
Prints 'seven world'.
william at cycronsystems dot com
I couldn't find a way to Trim an array in PHP so i wrote this little function that seemed to do the trick. It will trim the array down to a specified size
<?php
//Utility Function to Trim Array
){
$newArray = array();
for(++){
]);
}
return (array)$newArray;
}
?>
Example:
var_dump($treatList);
array(3) {
["id"]=>
string(3) "476"
["categoryID"]=>
string(2) "49"
["title"]=>
string(55) "80% off Sidewalk Crawling Classes from Urban Adventures"
$treatList = trim_array($listist,2);
Will result in:
var_dump($treatList);
array(2) {
["id"]=>
string(3) "476"
["categoryID"]=>
string(2) "49"
zachera
function array_closest_key($needle,$haystack){
foreach($haystack as $key => $value){
if($needle <= $value){
return $key;
}
}
}
Get the closest key to the specified $needle out of $haystack.
dtomasiewicz at gmail dot com
<?php
/**
* Functions for examining and manipulating matrices (n-dimensional arrays) of data
* with string dot-separated paths. For example, you might do this with multidimensional
* array:
* $var = $array['someKey']['cats']['dogs']['potato'];
*
* Accomplishing this can be a nightmare if you don't know the depth of the path or the array
* is of a variable dimension.
*
* You can accomplish the same by using $array as a Matrix:
* $array = new Matrix($array);
* $var = $array->get('someKey.cats.dogs.potato);
*
* @author Daniel Tomasiewicz <www.fourstaples.com>
*/
class Matrix {
private $data;
public function = array()) {
;
}
/**
* Gets the value at the specified path.
*/
) {
if() {
return ;
}
);
;
for(++) {
if(isset(]])) {
]];
} else {
return null;
}
}
if(isset(]])) {
return ]];
} else {
return null;
}
}
/**
* Sets a value to a specified path. If the provided value is
* null, the existing value at the path will be unset.
*/
) {
if()) {
foreach() {
);
}
} else {
);
;
for(++) {
if(!isset(]])) {
]] = array();
}
]];
}
if() {
foreach() {
];
}
} elseif(]])) {
unset(]]);
} else {
;
}
}
}
/**
* Returns a flattened version of the data (one-dimensional array
* with dot-separated paths as its keys).
*/
) {
);
if() {
;
} else {
;
}
$flat = array();
foreach() {
if()) {
);
} else {
;
}
}
return $flat;
}
/**
* Expands a flattened array to an n-dimensional matrix.
*/
) {
();
foreach() {
);
}
return $matrix;
}
}
?>
john at nowhere dot com
If you ever wondered if you can do something like:
<?php
$a ] ;
?>
The answer is no, you can't. But you can use the following function. I named it i() because it's a short name and stands for "to index".
<?php
/**
* Usage: i( $array, $index [, $index2, $index3 ...] )
*
* This is functionally equivalent to $array[$index1][$index2][$index3]...
*
* It can replace the more prolix
*
* $tmp = some_function_that_returns_an_array() ;
* $value = $tmp['some_index']['some_other_index'] ;
*
* by doing the job with a single line of code as in
*
* $value = i( some_function_that_returns_an_array(), 'some_index', 'some_other_index' ) ;
*
* Note that since this function is slower than direct indexing, it should only be used in cases like the one
* described above, for improving legibility.
*
* @param $array
* @param $index
* @param [optional] $index2, index3, ...
* @throws Exception when the indexes do not exist
*/
function i(){
();
//gets the fist parameter, $array
;
unset(//because indexes[0] is actually not an index, but the first parameter, $array
){
if( (! )) ){
throw new ));
}
];
}
return $array;
}
?>
aaron at tekserve dot com
Here's a function to recursively convert objects to arrays and remove the special characters from private and protected variables. I use it with XML_Serializer to convert objects to XML.
<?php
) {
if(;
if()) {
$new = array();
foreach() {
);
);
}
}
else ;
return $new;
}
?>
unix at bujanoci dot net
Just in case someone finds it usefull.
If you want to capitalize the first letter of each word in the array you could:
<?php
$myarray );
);
);
echo $j;
?>
This will return: One , Two , Three , Four , Etc..
Probably it's not worth of posting it, but just thought beginners might find it usefull.
Anonymous
This is a modification of a function like this which works with two dimensional arrays. Pass a 2d array to this function and my function will return an array of the arrays with the specified key-value pair (specified by $key and $value).
<?php
)
{
$ret = array();
for (++)
{
if ()
];
}
return $ret;
}
?>
Martin
You can actually create arrays in arrays; just consider the following code:
<?php
)
{
);
foreach()
{
);
])
}
);
?>
A (.csv-)file is loaded into the function LoadData and stored in the array $lines. Then foreach puts the values from the $lines-array into $line and $i is defined as an array of the array $line. Please note that this type of code could take up much of CPU-usage; it generates a multi-dimensional array.
When $i is printed (in the example, value 1 of the array) it would display:
Array ( [0] => Array (
[0] => 7;75;X;0;0;1;0;3;Gr;Br;Do;0;0;0;0;0;0;0;0;
[1] => ;200;K;0;0;0;0;0;Gr;0;0;0;0;ZL;0;0;0;0;0;
[2] => ;260;Z;;;;;;Gr;;;;;VL;;;;;;
[3] => ;270;K;;;;1;;Gr;Br;Li;;;;;;;;;
[4] => ;500;V;;;;;;Br;;;;;;;;;;;
[5] => 6;60;X;;;;;;;;;;;;;;;;;
[6] => ;80;K;;;;;;Gr;;;;;ZL;;;;;;
[7] => ;210;Z;;;;;;Gr;;;;;;;;;;;
)
webmaster at oehoeboeroe dot nl
A simple function to check if you can use your variable as an array offset validly and without getting it typecasted.
<?php
) {
return ;
}
;
// true
;
// false
;
// true
;
// true
;
// false
;
// false
;
// false
$h = array();
// false
;
// false
?>
genix at arctoz dot de
Hello,
to check if an element was set is actually pretty simple:
<?php
$array ,
'sec' => 2
);
;
echo $out;
?>
greets,
genix
Dawid Krysiak
Trying to get array element that was not set, throws ERROR_NOTICE and returns NULL. Example:
<?php /* php v.4.4.7 */
$array = array(
,
,
);
// Notice: Undefined index: pear in /path/to/file.php on line 123
// NULL
?>
Haven't found that mentioned on this page.
hek at theeks dot net
Note that NULL is not exactly a scalar value, so the following two lines of code do NOT produce identical arrays.
<?php
$x // $x ends up an empty array (zero elements)
// $y ends up an array containing one element (a null)
?>
pinkgothic at gmail dot com
Re: fmouse,
the phenomenom you're describing pertains to superglobals, not arrays, and it only applies in a very specific scope. Check out http://de.php.net/manual/en/language.variables.variable.php :
"Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically."
frywater
>fmouse
Variable variables can be used with arrays as discussed in the variable variable section.
Also, from your code, $somevar can be an array and still work fine.
$fum = "somevar";
$$fum = array(); // $somevar is now an array
$foo = $$fum;
print_r( $foo); // we get an empty array printed
print_r() doesn't just print arrays, it prints any variable type.
If you pass it a variable, that hasn't been defined yet, it won't know how to print it.
You would get this same results by passing any undefined variable such as:
print_r( $bar ); // PHP Notice: undefined variable ...$bar
fmouse at fmp dot com
Using variables as array names no longer works in PHP5.
$fum = "somevar";
$foo = $$fum;
# Still works if $somevar isn't an array. $foo contains the value of $somevar
but ....
$fum = "_POST";
print_r($$fum);
print_r(${$fum});
Neither form of indirection works in this context. $$fum comes back empty.
If you have PHP4 code that used this kind of indirection you can work around the change in PHP5 using an eval().
$fum = "_POST";
$foo = eval("return $$fum;");
print_r($foo);
This works!
rama dot devi at gmail dot com
Sorting double dimensional arrays by a specified key bothe for Strings and for integers:
Ex:
$personDetails = array( array("firstName" => "Nancy", "lastName" => "Grace", "age" => 22), array("firstName" => "Andy", "lastName" => "Peter", "age" => 28), array("firstName" => "Jim", "lastName" => "Gary", "age" => 25), array("firstName" => "Lary", "lastName" => "James", "age" => 28), array("firstName" => "Peter", "lastName" => "David", "age" => 17), array("firstName" => "Raj", "lastName" => "King", "age" => 9), array("firstName" => "John", "lastName" => "Baxter","age" => 35) );
//To sort the array by firstName:-
function sortFirstName($p1, $p2) {
return strnatcmp($p1['firstName'], $p2['firstName']);
}
usort($personDetails, 'sortFirstName');
//To sort by an integer Field
function sortByInteger(&$personDetails, $field) {
$sort = "return strnatcmp(\$p1['$field'], \$p2['$field']);";
usort($personDetails, create_function('$p1,$p2', $sort));
return $personDetails;
}
$personDetails = sortByInteger($personDetails, 'age');
//To sort the array in Descending order by a key, It can be done by adding "-" sign before strnatcmp() function.
I hope this helps
ken underscore yap atsign email dot com
"If you convert a NULL value to an array, you get an empty array."
This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.
$values = search(...);
Now you want to merge the array with another array. What do we do if $values is NULL? No problem:
$combined = array_merge((array)$values, $other);
Voila.
pepesantillan at gmail dot com
z on 22-Apr-2005 12:10 wrote:
-----------------------------------------------
Here's a simple function to insert a value into some position in an array
<?php
)
{
);
;
);
return $array;
}
?>
and now for example...
<?php
$a );
);
?>
Now $a will be "John","Mike","Paul","Peter"
-----------------------------------------------
Im learning to use PHP and reading about array_splice found that
<?php
)
{
);
;
);
return $array;
}
);
);
);
?>
would output the same as
<?php
$b );
));
);
?>
SID TRIVEDI
<?php
//Simple Login Script using associative array.
//You may modify the codes and use $_POST['FORM_FIELD_DATA'] for your web-page.
//You may spice-up the codes with more form field validation & security features.
//$user_name=$_POST['user_name'];
//$password=$_POST['password'];
//for testing purpose only
//for testing purpose only
;
;
// here user_name is key and password is the value of an array..
// website owner has to add new user/site member manually in $login_array
$login_array = array(
,
,
,
,
,
);
);
);
if (isset(]))
{
];
if ()
{
echo //may redirect to specific webpage.
}
else
{
echo "Please try again!"; //may redirect to Error page.
}
}
else
{
echo "Please register with us. Thanks!"; //may redirect to registration page.
exit();
}
echo("\n<br>");
echo 'Thanks to Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski for wonderful PHP!';
?>
carl at linkleaf dot com
Its worth noting that there does not appear to be any functional limitations on the length or content of string indexes. The string indexes for your arrays can contain any characters, including new line characters, and can be of any length:
<?php
$key = "XXXXX";
);
for (++) {
;
);
;
}
echo "<pre>";
);
echo "</pre>";
?>
Keep in mind that using extremely long array indexes is not a good practice and could cost you lots of extra CPU time. However, if you have to use a long string as an array index you won't have to worry about the length or content.
Gautam
<?php
//EXAMPLE of Multi-Dimentional Array where as an array's keys are an array itself.
//It's so easy to create one like this.
=>
array(,
,
,
,
),
'Comedy' =>
array (,
,
));
//You may switch type from Action to Comedy.
// You may switch hero from Pearce Brosnan to Jim Carrey.
);
// produces browser output as under:
// Pearce Brosnan 's Action movie is Die Another Day.
?>
Olegk, getmequick[at]gmail[dot]com
Hey..
here is a function which helps to avoid using empty/isset
checkings for arrays.
(it's acts simillar to 'default' modifier in Smarty)
Using this function you will avoid 'Undefined index' or
'Undefined offset' error.
<?php
$_POST;
/*
key exist (same as $_POST['id'][other])
*/
);
/*
key doesn't exist, we get default value (same as $_POST['var'])
*/
);
function )
{
);
);
];
;
if( ) {
);
}
elseif( ) {
);
}
elseif( ) {
);
}
elseif( ) {
);
}
if (! $ret )
return $default;
else
return $ret;
}
/**
@access private
*/
)
{
static $ret;
if( ) ) {
if( ) {
]];
}
elseif( ) {
);
}
}
return $ret;
}
?>
Hope this will help someone!
conorj
Another note on unquoted array indices. Because it is first interpreted as a constant, it must obey the naming convention of constants. i.e. a letter or underscore followed by optional letter, digit and/or underscore characters.
Therefore while the following array declaration is legal:
$a = array('1st'=>'First','2nd'=>'Second');
Trying to access either array item as follows causes an error:
$first = "$a[1st]";
$second = "$a[2nd]";
moehbass at gmail dot com
<b>Mark Gukov</b> wrote below:
Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.
The following works fine:
<?php
$r;
echo ;
?>
...but in the case of multi-dimensional arrays:
<?php
$r;
echo ;
?>
would result in "Array[c] is tasty."
-----------------------------------------------------------------
However, the following runs fine;
$r['a']['b'] = 'banana';
echo "{$r[a][b]} is tasty.";
Just box it!
don dot hosek at gmail dot com
It's slightly faster to use array_splice to remove an element of an array:
array_splice($array, $index, 1)
than to do it using the suggested method of unset and reindex:
unset($array[$index]);
$array = array_values($array);
The difference, however, is very small. With 950 iterations I had times of
unset and reindex: 0.22837495803833
splice: 0.22392416000366
lesantoso at yahoo dot com
This Indonesian number speller function is twice
faster(*) than the one provided in class Terbilang by
anghuda(at)gmail(dot)com (25-May-2006 08:52):
http://www.lesantoso.com/terbilang.html
(*) 2.1 vs. 4.2 seconds in processing 10000 random numbers
Spudley
On array recursion...
Given the following code:
<?
$myarray = array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?>
The print_r() will display *RECURSION* when it gets to the third element of the array.
There doesn't appear to be any other way to scan an array for recursive references, so if you need to check for them, you'll have to use print_r() with its second parameter to capture the output and look for the word *RECURSION*.
It's not an elegant solution, but it's the only one I've found, so I hope it helps someone.
kal at kalunite dot com i mean dot net
About the automatic conversion of bare strings...
My opinion is that it never should have been implemented. Isn't it easier to NOT implement this "handy" feature in the first place? It is such a convenient way for "smart" programmers to write unsafe, not-futureproof code. Please remove this feature from future versions of PHP, please. (Hey, if you could change the OOP mechanisms between PHP 4 and PHP 5, why can't you make this change, right?)
This page should include details about how associative arrays are implemened inside PHP; e.g. using hash-maps or b-trees.
This has important implictions on the permance characteristics of associative arrays and how they should be used; e.g. b-tree are slow to insert but handle collisions better than hashmaps. Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions. These factors have implictions on how associative arrays should be used.
Mark Gukov
Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.
The following works fine:
<?php
$r;
echo ;
?>
...but in the case of multi-dimensional arrays:
<?php
$r;
echo ;
?>
would result in "Array[c] is tasty."
petruzanautico at yahoo dot com dot ar
Regarding the message of phoenixbytes:
The line foreach($bad as $baddies); will just yield in $baddies the last value of the array $bad.
I think that wasn't your intention, in that case there are faster and better ways than foreach.
I think what you wanted to do is:
<?php
// make a collection
{
if (// find a match
{
;
}
else
{
;
}
} // foreach end
?>
php dot net at todandlorna dot com
in response to ch dot martin at gmail dot com
If you are using the following code:
<?php
$r );
foreach ()
);
?>
and you need the array key '35' to be a string (for looping maybe), you can make sure the key is a string by appending a 0 on the front.
'035' instead of '35'
ch dot martin at gmail dot com
Extremely irritating quirk regarding the variable types of array keys:
<?php
$r );
foreach ()
);
?>
The first var_dump for '05' is:
string(2) "05"
as expected. But the second, '35', turns out as:
int(35)
Php apparently decided to make the 35 became an int, but not the 05 (presumably because it leads with a zero). As far as I can see, there is absolutely no way of making string(2) "35" an array key.
anghuda(at)gmail(dot)com
this is simpler tha function display_angka_bilangan by ktaufik(at)gmail(dot)com (16-Feb-2005 12:40)
<?
/*
*
* Class : Terbilang
* Spell quantity numbers in Indonesian or Malay Language
*
*
* author: huda m elmatsani
* 21 September 2004
* freeware
*
* example:
* $bilangan = new Terbilang;
* echo $bilangan -> eja(137);
* result: seratus tiga puluh tujuh
*
*
*/
Class Terbilang {
function terbilang() {
$this->dasar = array(1=>'satu','dua','tiga','empat','lima','enam',
'tujuh','delapan','sembilan');
$this->angka = array(1000000000,1000000,1000,100,10,1);
$this->satuan = array('milyar','juta','ribu','ratus','puluh','');
}
function eja($n) {
$i=0;
while($n!=0){
$count = (int)($n/$this->angka[$i]);
if($count>=10) $str .= $this->eja($count). " ".$this->satuan[$i]." ";
else if($count > 0 && $count < 10)
$str .= $this->dasar[$count] . " ".$this->satuan[$i]." ";
$n -= $this->angka[$i] * $count;
$i++;
}
$str = preg_replace("/satu puluh (\w+)/i","\\1 belas",$str);
$str = preg_replace("/satu (ribu|ratus|puluh|belas)/i","se\\1",$str);
return $str;
}
}
?>
benjcarson at digitaljunkies dot ca
phoenixbytes: The regex you have posted for matching email addresses is incorrect. Among other things, it does not allow '+' before the '@' (which is perfectly valid and can be quite useful to separate extensions of a single address). RFC 822 [1] defines the grammar for valid email addresses, and (the extemely long) regex implementing can be found at [2]. Even the "Add Note" page here at php.net says:
[quote]
And if you're posting an example of validating email addresses, please don't bother. Your example is almost certainly wrong for some small subset of cases. See this information from O'Reilly Mastering Regular Expressions book for the gory details.
[/quote]
A note to others: please do your homework before writing another email-matching regex.
[1] http://www.ietf.org/rfc/rfc0822.txt?number=822
[2] http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.
phoenixbytes at o2 dot co dot uk
i use the array() function for deciding upon an email address's validity, i have a 'wap stalker' of my site that loves to exploit every hole i leave, so i used the following script to avoid being email bombed with my own file sender script, the array() is used to filter out undesirable email providers and, of course, any and all of my own addresses. before all that i used a REGEX to make sure it's an actual email address before going any further.
$mailto = "mail.domain.org"; // the input to be tested
if (preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i", $mailto)) // see if it's really an email address
{
$bad = array('mytrashmail.com', 'mymail.ro', 'acasa.ro', 'gala.net', 'phoenixbytes'); // pick out the victims
foreach($bad as $baddies); // make a collection
if (preg_match("/$baddies/i", $mailto)) // find a match
{
$addrmail = "false";
}
else
{
$addrmail = "true";
}
}
else
{
$addrmail = "false";
}
$addrmail can then be used in an argument.
$baddies can be used to give a list, if necessary.
i hope this helps someone.
crozzer
Passing variables into the array constructor:
Just a NOOB pointer, I couldn't find other examples for this. If you want to pass the value of an existing variable into the array() constructor, you can quote it or not, both methods are valid.
<?
$foo_value = 'foo string';
$bar_value = 'bar string';
$myArray = array(
'foo_key' => $foo_value, // not quoted
'bar_key' => "$bar_value"); // quoted
foreach ($myArray as $k => $v) {
echo "\$myArray[$k] => $v.<br />\n";
}
?>
Both of these will work as expected, but the unqoted $foo_value method above is marginally faster because adding quotes adds an additional string de-reference.
sales at maboom dot ch
if you need to check a multidimensonal array for values it's handy to store it like
$ar['key1'][0]
$ar['key2'][0]
$ar['key3'][0]
$ar['key1'][1]
$ar['key2'][1]
$ar['key3'][1]
and to loop the keys.
Fill the array (from a database-request):
while($rf=mysql_fetch_row($rs))
{
$nr=$rf[0];
$channel['nr'][$nr]=$rf[1];
$channel['chatter'][$nr]=$rf[2];
}
Call the values:
foreach(array_keys($channel['nr']) as $test)
{
print ' nr:'.$test.'<br>';
print 'value nr: '.$channel['nr'][$test].'<br>';
print ' chatter: '.$channel['chatter'][$test].'<br>';
}
This is useful, if you have to look later for an element
inside the array:
if(in_array($new_value,$channel['nr'])) print 'do something.';
Hope this helps someone.
ia [AT] zoznam [DOT] sk
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:
<?php
)
{
;
}
// without next line you can get bad results...
//unset( $value );
;
?>
Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').
Bad results can also appear in nested foreach loops (the same reason as above).
So either unset $value after each foreach or better use the longer form:
<?php
)
{
;
}
?>
stochnagara at hotmail dot com
Regarding the previous comment, thw following code does the job:
<?php
) {
;
}
?>
jazepstein OverAt GeeMail dot com
Regarding the previous comment, the fact that this code has no effect is perfectly expected:
<?php
) {
;
}
?>
The reason that this doesn't work, is because each time that PHP goes through the loop, it _copies_ the value of the array element into $value. So if you assign a new value to the data in $value, it has no effect on the actual array, because you only changed the value of the copy that was put in $value.
As was discovered in the previous post, the only way to get around this problem is to change the value in the original array. Hence, a typical foreach should instead look like this:
<?php
) {
;
}
?>
caifara aaaat im dooaat be
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]
Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...
I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:
<?php
$a1 );
);
);
foreach( ) {
;
}
);
/* nothing changed result is:
Array
(
[0] => Array
(
[a] => 0
[b] => 1
)
[1] => Array
(
[aa] => 0
[bb] => 11
)
) */
) {
;
}
);
/* now it works, this prints
Array
(
[0] => Array
(
[a] => 0
[b] => 1
[c] => 3
)
[1] => Array
(
[aa] => 0
[bb] => 11
[c] => 3
)
)
*/
?>
uzakufuklar at hotmail dot com
It is a kind of simple muti-dimensional array list.
I have made it just to give a simple idea.
<?php
echo "Here we'll see how to create a multi-dimensional array.\n";
,
),
),
,
'third')
);
foreach(){
foreach(){
echo $counter;
}
}
?>
z
Here's a simple function to insert a value into some position in an array
<?php
)
{
);
;
);
return $array;
}
?>
and now for example...
<?php
$a );
);
?>
Now $a will be "John","Mike","Paul","Peter"
jeff splat codedread splot com
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:
<html>
<body>
<?php
printf);
?>
<form method="post" action="">
<input type="hidden" value="Sux">
<input type="submit" value="Click" />
</form>
</body>
</html>
Once you click on the button, the page displays the following:
POST: Array ( [Windows3_1] => Sux )
roland dot swingler at transversal dot com
Something that tripped me up:
If you mix string and integer keys, be careful if you are doing a comparison on the to find if a string key exists.
For example, this will not do what you expect it to do:
<?php
$exampleArray = array();
;
;
;
foreach (){
if (){
print "Found Key";
}
}
?>
It will print "Found Key", because (I presume) when PHP makes the comparison between the string "correctKey" and the index 0, it casts the string to an integer, rather than casting 0 to the string "0" and then doing the comparison.
Using === fixes the problem:
<?php
){
if (){
print "Found Key";
}
}
?>
lars-phpcomments at ukmix dot net
Used to creating arrays like this in Perl?
@array = ("All", "A".."Z");
Looks like we need the range() function in PHP:
<?php
$array ));
?>
You don't need to array_merge if it's just one range:
<?php
$array );
?>
mortoray at ecircle-ag dot com
On array copying a deep copy is done of elements except those elements which are references, in which case the reference is maintained. This is a very important thing to understand if you intend on mixing references and recursive arrays.
By Example:
$a = array( 1 );
$aref_a = array( &$a );
$copy_aref_a = $aref_a;
$acopy_a = array( $a );
$copy_acopy_a = $acopy_a;
$a[] = 5;
$acopy_a[0][] = 6;
print_r( $aref_a ); //Shows: ( (1,5) )
print_r( $copy_aref_a ); //Shows: ( (1,5) )
print_r( $acopy_a ); //Shows: ( (1, 6) )
print_r( $copy_acopy_a ); //Shows: ( (1) )
ktaufik(at)gmail(dot)com
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.
Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.
In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"
<?php
//build random 3 digit number to be "said" in Bahasa Indonesia
);
);
);
function ) {
$angka = array(
,
,
,
,
,
,
,
,
9 => 'sembilan'
);
return ];
}
// Terbilang X-------Say X
;}
elseif (;}
else {;}
// Terbilang Y ------Say Y
;}
elseif (;}
elseif (;}
elseif (;}
else {;}
// Terbilang z ------Say z
;}
elseif (;}
elseif (;}
elseif();}
elseif (;}
else {);};
;
echo ;
echo $terbilang;
?>
Hope it is useful
ktaufik(at)gmail(dot)com
db
[Editor's Note: (Second example.) These are not "arrays in arrays". These are single-dimensional arrays containing stdClass objects; all objects are referenced by default in PHP5. You can see in the var_dump output that they point to the same object.]
Attention with Arrays in Arrays!
If you copy (=) an array which contains arrays it will be REFERENCED not COPIED.
Example:
<?php
/* GOOD ONE */
echo "<b>Here copy (=) works correct:</b><br>";
/* Initialise Array 1 */
));
/* COPY Array */
;
/* Change some values in Array 2 */
;
;
echo "<b>Original:</b><pre>";
);
echo "</pre><b>Changed Copy:</b><pre>";
);
/* BAAAAAAAD ONE */
echo "</pre><hr><b>Here copy (=) FAILS:</b><br>";
/* Initialise Array 1 */
;
;
;
;
/* COPY Array */
;
/* Change some values in Array 2 (!) */
;
;
echo "<b>Original:</b><pre>";
);
echo "</pre><b>Changed Copy:</b><pre>";
);
echo "</pre>";
php?>
The output of $a1 and $a2 will be the same..
Joe Morrison <jdm at powerframe dot com>
Programmers new to PHP may find the following surprising:
<?php
$x;
;
echo "Original array:\n";
);
);
echo "Array after popping last element:\n";
);
?>
The surprise is that element 0 is deleted, not element 1. Apparently the notion of "last element" has more to do with how the array is stored internally than with which element has the highest numeric index. I recently translated a Perl program to PHP and was bitten by this one.
My solution was to identify all the places in my code where I could prove that the array elements were assigned sequentially. In those cases it is safe to use array_pop, array_splice, etc. since the array indices correspond with the array layout. For the other cases, my solution was to write replacements for the built-in array functions such as this one:
<?php
)
{
if (!isset($a))
return;
if (!))
return;
if ()
return;
unset())]);
}
?>
Cameron Brown
Negative and positive array indices have different behavior when it comes to string<->int conversion. 1 and "1" are treated as identical indices, -1 and "-1" are not. So:
$arr["1"] and $arr[1] refer to the same element.
$arr["-1"] and $arr[-1] refer to different elements.
The following code:
<?
$arr[1] = "blue";
$arr["1"] = "red";
$arr[-1] = "blue";
$arr["-1"] = "red";
var_dump($arr);
?>
produces the output:
array(3) {
[1]=>
string(3) "red"
[-1]=>
string(4) "blue"
["-1"]=>
string(3) "red"
}
This code should create an array with either two or four elements. Which one should be the "correct" behavior is an exercise left to the reader....
akamai at veloxmail dot com dot br
It is quite simple, but don't forget when you'll using foreach with forms arrays.
If your field name is:
<input type="checkbox" ...
It doesn't work.
This should work:
<input type="checkbox" ...
agape_logos at shaw dot ca
I was having trouble getting javascript arrays and php arrays to work together with a Check All checkboxe. Here is a simple solution. Clicking the 'Check All' checkbox will check all checkboxes on the form.
<script language="JavaScript">
function chkAll(frm, arr, mark) {
for (i = 0; i <= frm.elements.length; i++) {
try{
if(frm.elements[i].name == arr) {
frm.elements[i].checked = mark;
}
} catch(er) {}
}
}
</script>
<form>
<input type="checkbox" value="1">
<?php
++){
echo();
}
?>
</form>
Dean M.
chroniton .at. gmx .dot. li
I didn't find this anywhere in the docs and i think it is worth a mention:
$a[] = &$a;
print_r($a);
// will output:
/*
Array
(
[0] => Array
*RECURSION*
)
*/
// this means that $a[0] is a reference to $a ( that is detected by print_r() ). I guess this is what the manual calls 'recursive arrays'.
"Using NULL as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets."
If you create an array like this:
$foo = array(null => 'bar');
And then want to access 'bar', you must use this syntax:
echo $foo['']; // notice the two single quotes
This will of course cause a fatal error:
echo $foo[];
wmoranATpotentialtechDOTcom
Dereferencing arrays takes some time, but is not terribly expensive.
I wrote two dummy loops to test performance:
for ($i =0; $i < count($a); $i++) {
$x = $a[$b[$i]];
$y = $a[$b[$i]];
$z = $a[$b[$i]];
}
for ($i =0; $i < count($a); $i++) {
$q = $b[$i];
$x = $a[$q];
$y = $a[$q];
$z = $a[$q];
}
The first loop is 6.5% slower than the second. Meaning that dereferencing arrays is not terribly expensive, unless you do it a whole lot. I would expect that each extra reference costs about 3% in speed. The lesson is that if you're going to be using a specific value in an array for a number of operations, you can gain a little speed by assigning it to a temp variable (or creating a reference with $q = &$b[$i]) but it's not worth getting crazy over.
I tested this with iterations of 10,000 and 100,000 on php 4.2 and the results were consistent.
mu at despammed dot com
Recursive arrays and multi-dimensional arrays are the same thing and completely identical.
The following confirms this:
$fruits1["european"]["green"] = "Apple";
$fruits2 = array ( "european" => array ( "green" => "Apple"));
print ($fruits1 === $fruits2);
Result: 1 (= true)
hramrach_L at centrum. cz ;-)
Arrays can be merged using + as discussed in the notes for array_merge.
http://www.php.net/manual/en/function.array-merge.php
philip at boone dot at
For all of you having problems when using php arrays in an HTML form input field name, and wanting to validate the form using javascript for example, it is much easier to specify an id for the field as well, and use this id for validation.
Example:
<input type="text">
then in the javascript check:
if(formname.lastname.value == "") {
alert("please enter a lastname!");
}
This works very well. If you have any problems with it, let me know.