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."
배열
PHP에서 배열은 실질적으로 순서가 있는 맵이다. 한 맵은 values를 keys로 맵핑하는 타입이다. 이 타입은 몇가지 목적에 의해 옵티마이징될수 있다. 그래서 그 타입을 실제 배열이나 리스트(vector), 해쉬테이블(map의 구현), 딕셔너리(dictionary), 컬렉션(collection), 스택(stack), 큐(queue), 등등으로 사용할수 있다. 다른 PHP 배열을 값으로 갖을수 있기 때문에, 트리(tree)를 아주 쉽게 시뮬레이션할수 있다.
그런 데이터 구조(자료 구조)는 이 매뉴얼의 범위를 벗어난다. 그러나 그들 각각의 예를 최소한 하나는 발견할수 있을것이다. 자세한 정보를 위해 이 광범위한 주제에 대한 참고서적을 제시해줄것이다.
문법
array()함수로 명기
array는 array() 언어-구조에 의해 생성될수 있다. 이 함수는 콤마로 구분되는 몇 개의 key => value쌍을 취할수 있다.
array( key => value , ... ) // key may be an integer or string // value may be any value
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
key는 integer나 string타입이 될수 있다. key가 표준적인 integer타입이면, 그 값으로 해석될것이다 (즉, "8"은 8로 해석되는 반면, "08"은 "08"로 해석된다). PHP에서 인덱스 배열과 연관 배열 사이는 아무 차이가 없다; 오직 하나의 배열 타입만이 있는데, 그 배열은 정수나 문자열 인덱스를 모두 포함할수 있다.
값은 모든 종류의 PHP 타입이 될수 있다.
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?>
주어진 값에 대한 key를 표기하지 않으면, 정수 인덱스의 최대값이 취해져서 새로운 key는 최대값 + 1이 될것이다. 이미 값을 보유하고 있는 key를 지정하게 되면, 그 값은 덮어씌어질것이다.
<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
PHP 4.3.0에서는 위에서 설명한 인덱스 생성 동작이 변경되었다. 즉, 현재 최대 key가 음수인 배열에 추가동작이 발생하면, 다음 key는 제로 (0)가 될것이다. 전에는, 새로운 인덱스는 기존의 가장 큰 key + 1로 되었었다. 양수의 인덱스에는 같은 동작을 한다.
key로 TRUE를 사용하는 것은 integer 1 key가 될것이다. key로 FALSE를 사용하면 integer 0 key가 될것이다. key로 NULL을 사용하면 빈 문자열로 취급될것이다. key로 빈문자열을 사용하는 것은 빈 문자열을 갖는 key를 만들고 그 값을 생성 (또는 덮어씀)한다; 빈 대괄호를 사용하는것과는 다르다.
key로 배열이나 객체를 사용할수 없다. 그렇게 하면 다음과 같은 경고가 발생할것이다: Illegal offset type.
대괄호 문법을 사용하여 생성/변경
그 안에 값을 명시적으로 표시함으로써 기존의 배열을 변경할수 있다.
이와 같은 일은 대괄호 안에 key를 표시함으로해서 배열에 값을 지정하여 수행한다. key를 빼먹을수도 있고, 그 경우에 변수명에 빈 대괄호("[]")를 추가한다.
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value$arr이 아직 존재하지 않으면, 생성될것이다. 그래서 이 방법이 배열을 표현하는 대안이 된다. 어떤 값을 변경하려면, 그 key로 표현되는 요소에 새로운 값을 지정한다. key/value 쌍을 제거하려면, 그것을 unset()할 필요가 있다.
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
Note: 위에서 설명한바와 같이, key가 없는 대괄호를 사용한다면, 존재하는 정수 인덱스의 최대값이 취해질것이고, 새로운 key는 최대값의 + 1이 될것이다. 정수 인덱스가 아직 존재하지 않으면, key는 0(제로)가 될것이다. 이미 값을 보유하고 있는 key로 지정하면, 그 값은 덮어 씌어질것이다.
WarningPHP 4.3.0에서는 위에서 설명한 인덱스 생성 동작이 변경되었다. 즉, 현재 최대 key가 음수인 배열에 추가동작이 발생하면, 다음 key는 제로 (0)가 될것이다. 전에는, 새로운 인덱스는 기존의 가장 큰 key + 1로 되었었다. 양수의 인덱스에는 같은 동작을 한다.
이 목적을 위한 최대 정수 key는 현재까지는 배열 안에 존재할 필요가 없다. 단순히 배열을 마지막으로 인덱스 한 이후 어떤 시간내에 배열 안에 존재해야 한다. 다음 예를 보면:
<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5, instead of 0 as you
// might expect).
$array[] = 6;
print_r($array);
// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>위 예제 코드는 다음을 출력할것이다:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
유용한 함수
배열을 위한 유용한 함수가 지원된다. 배열 함수 섹션을 볼것.
Note: unset()함수는 항상 배열의 key를 unset한다. 배열이 다시 인덱스되지 않을것이라는것에 주의한다. 오직 "가용한 정수 인덱스"를 사용한다면(제로에서 시작해서, 하나씩 증가), array_values()를 사용하여 재인덱싱 효과를 수행할수 있다.
<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
$a = array(1 => 'one', 3 => 'three');
and NOT
$a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Now b is array(0 => 'one', 1 =>'three')
?>
foreach 제어 구조는 배열을 위해 특별히 지원되는것이다. 배열 안을 이동하는 가장 빠른 방법을 제공한다.
배열이 하는것과 하지 않는것
왜 $foo[bar]이 잘못인가?
항상 문자열 리터럴 배열 인덱스 주위에는 따옴표를 사용해야 한다. 예를 들면, $foo['bar']을 사용하고 $foo[bar]은 사용하지 말라. 그러나 왜 $foo[bar]이 잘못인가? 오래된 스크립트에서 다음 문법을 볼수 있을것이다:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
Note: 위 말은 항상 key를 따옴표 처리하라는 것이 아니다. 상수나 변수가 PHP에서 해석되는것을 방지하기 위해 key에서 이들을 따옴표처리하지 않을수 있다.
위 예제코드의 출력은 다음과 같다:<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nChecking $i: \n";
echo "Bad: " . $array['$i'] . "\n";
echo "Good: " . $array[$i] . "\n";
echo "Bad: {$array['$i']}\n";
echo "Good: {$array[$i]}\n";
}
?>Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2
위 사실을 설명하는 몇가지 예제 코드:
<?php
// Let's show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// Let's define a constant to demonstrate what's going on. We
// will assign value 'veggie' to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay as it's inside a string. Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]"; // Hello apple
// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using autoglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
E_NOTICE 레벨 에러(E_ALL로 설정) 를 보이기 위해 error_reporting()함수를 쓸때, 다음과 같은 에러를 보게 될것이다. 기본값으로, error_reporting은 그들을 보여주지 않는다.
문법 섹션에서 설명한대로, 대괄호('[' 과 ']') 사이에 표현식이 존재해야 한다. 이 말의 의미는 다음과 같은 코드를 쓸수 있다는 뜻이다:
<?php
echo $arr[somefunc($bar)];
?>
<?php
$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
?>
<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>
위 예에서 이미 설명했듯이, $foo[bar]은 작동하지만 잘못되었다. 이 코드는 작동한다. 왜냐하면 이 문법에서 bar는 상수 표현으로 인식될수도 있기 때문이다. 하지만, 이 경우에 bar란 이름을 갖는 상수는 존재하지 않는다. PHP는 문자그대로 bar를 표시했다고 인식해서 문자열 "bar"으로 보기 때문이다. 따옴표 쓰는것을 잊었다고 인식한다.
그래서 그것이 왜 나쁜가?
미래의 어떤 시점에서, PHP 팀은 또다른 상수나 키워드를 추가할수도 있거나, 애플리케이션안에 또다른 상수를 사용할수도 있다. 그러면 이 경우에 어려움에 빠지게 된다. 예를 들면, empty와 default워드는 이런 이유로 사용할수 없다. 왜냐하면 그들은 특별한 예약 키워드이기 때문이다.
Note: 배반복하지만, 큰따옴표로 둘러싼 string안에서 "$foo[bar]"이 유효하도록 따옴표를 배열 인덱스에 둘러싸지 않는것이 유효한다. 그 이유에 대한 상세 설명을 위해 위 예제코드를 보는 것은 물론 문자열 안에서 해석되는 변수에 관한 섹션도 참고할것.
배열로 변환
다른 타입을 갖는: integer, float, string, boolean, resource, 어떤 값을 array로 변환한다면, 한개의 요소를 갖는 (인덱스 0) 배열을 얻을수 있다. 그 구성요소는 스칼라 값이다.
object를 배열로 변환하면, 각 객체의 속성(멤버 변수)를 배열의 구성요소로서 취할수 있다. key는 멤버 변수명이 된다.
NULL값을 배열로 변환하면, 빈 배열을 얻을수 있다.
비교하기
array_diff()와 배열 연산자를 사용하여 배열을 비교할 수 있습니다.
예제 코드
PHP에서 배열 타입은 다용도로 쓰인다. 그래서 여기서 배열의 완벽한 능력을 보이기 위해 몇가지 예제 코드를 보일것이다.
<?php
// this
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>
Example#1 array() 사용하기
<?php
// Array as (property-)map
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// strictly numerical keys
$array = array( 7,
8,
0,
156,
-10
);
// this is the same as array(0 => 7, 1 => 8, ...)
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
// empty array
$empty = array();
?>
Example#2 컬렉션
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
?>
출력은:
Do you like red? Do you like blue? Do you like green? Do you like yellow?
현재까지 배열의 값을 이런 루프 안에서 직접 변경하는 것은 불가능하다는 것에 주의해야 한다. 다음과 같은 편법이 있다:
Example#3 컬렉션
<?php
foreach ($colors as $key => $color) {
// won't work:
//$color = strtoupper($color);
// works:
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
출력은:
Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW )
이 예제 코드는 one-based 배열을 생성한다.
Example#4 One-based index
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
출력은:
Array ( [1] => 'January' [2] => 'February' [3] => 'March' )
Example#5 배열 채우기
<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
배열은 순서가 있다. 다양한 정력함수를 사용하여 그 순서를 변경할수도 있다. 더 자세한 정보는 배열 함수섹션을 참고. count()함수를 사용하여 배열 내의 아이템 수를 셀수 있다.
Example#6 배열 정렬하기
<?php
sort($files);
print_r($files);
?>
배열의 값은 어느것이든 될수 있기 때문에, 또한 다른 배열이 될수 있다. 이 방식으로 재귀적이고 다차원인 배열을 만들수 있다.
Example#7 재귀적이고 다차원인 배열
<?php
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
// Some examples to address values in the array above
echo $fruits["holes"][5]; // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]); // remove "first"
// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>
배열 지정은 항상 값 복사에 관련되어 있다는 것을 알고 있어야 한다. 참조에 의해 배열을 복사하려면 참조 연산자를 사용하여야 한다.
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
배열
13-Sep-2008 08:49
04-Jun-2008 04:43
>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
29-Apr-2008 01:14
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!
18-Mar-2008 02:52
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
09-Jan-2008 08:00
"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.
18-Dec-2007 04:25
z on 22-Apr-2005 12:10 wrote:
-----------------------------------------------
Here's a simple function to insert a value into some position in an array
<?php
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
?>
and now for example...
<?php
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>
Now $a will be "John","Mike","Paul","Peter"
-----------------------------------------------
Im learning to use PHP and reading about array_splice found that
<?php
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
print_r($a);
?>
would output the same as
<?php
$b = array("John","Paul","Peter");
array_splice($b,1,0,array("Mike"));
print_r($b);
?>
10-Oct-2007 02:14
<?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'];
$test_user_name = 'michelle_smith'; //for testing purpose only
$test_password = 'msmith321'; //for testing purpose only
$user_name = $test_user_name;
$password = $test_password;
// 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(
'user_name' => 'password',
'alex_duff' => 'alx321',
'xena78' => 'xena321',
'dela_pena' => 'delp321',
'shawn_1981' => 'shw81',
'michelle_smith' => 'msmith321');
ksort ($login_array);
reset($login_array);
if (isset($login_array[$user_name]))
{
$pass_check = $login_array[$user_name];
if ($password === $pass_check)
{
echo "Welcome, $user_name!\n<br>"; //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!';
?>
06-Sep-2007 11:36
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";
$test = array($key => "test5");
for ($x = 0; $x < 500; $x++) {
$key .= "X";
$value = "test" . strlen($key);
$test[$key] = $value;
}
echo "<pre>";
print_r($test);
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.
30-Aug-2007 01:56
<?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.
$movie_to_watch = array ('Action'=>
array('Kanu Reeves' => 'Matrix Reloaded',
'Pearce Brosnan' => 'Die Another Day',
'Tom Cruz' => 'Mission Impossible',
'Jason Statham' => 'Crank',
'Danzel Washington' => 'Man on Fire'),
'Comedy' =>
array ('Charlie Chaplin' => 'City Lights',
'Jim Carrey' => 'Cable Guy',
'Rowan Atkinson' => 'The Ultimate Disaster'));
$type_wanted = 'Action'; //You may switch type from Action to Comedy.
$hero_wanted = 'Pearce Brosnan'; // You may switch hero from Pearce Brosnan to Jim Carrey.
print ("$hero_wanted 's $type_wanted movie is " . $movie_to_watch[$type_wanted][$hero_wanted].".");
// produces browser output as under:
// Pearce Brosnan 's Action movie is Die Another Day.
?>
21-Aug-2007 02:59
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['id']['other'] = 'val1';
/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');
/*
key doesn't exist, we get default value (same as $_POST['var'])
*/
echo getRequestParam('var', 'default value');
function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;
if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);
}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}
if (! $ret )
return $default;
else
return $ret;
}
/**
@access private
*/
function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;
if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}
return $ret;
}
?>
Hope this will help someone!
14-Jul-2007 08:34
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]";
10-Jul-2007 05:41
<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['a'] = 'apple';
echo "$r[a] is tasty.";
?>
...but in the case of multi-dimensional arrays:
<?php
$r['a']['b'] = 'banana';
echo "$r[a][b] is tasty.";
?>
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!
23-May-2007 05:37
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
20-Mar-2007 03:14
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
16-Mar-2007 02:44
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.
16-Jan-2007 05:55
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.
27-Sep-2006 02:18
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['a'] = 'apple';
echo "$r[a] is tasty.";
?>
...but in the case of multi-dimensional arrays:
<?php
$r['a']['b'] = 'banana';
echo "$r[a][b] is tasty.";
?>
would result in "Array[c] is tasty."
21-Sep-2006 08:30
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
foreach($bad as $baddies) // make a collection
{
if (preg_match("/$baddies/i", $mailto)) // find a match
{
$addrmail = "false";
}
else
{
$addrmail = "true";
}
} // foreach end
?>
25-Jul-2006 04:28
in response to ch dot martin at gmail dot com
If you are using the following code:
<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
var_dump($key);
?>
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'
08-Jun-2006 11:40
Extremely irritating quirk regarding the variable types of array keys:
<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
var_dump($key);
?>
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.
25-May-2006 06:52
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;
}
}
?>
09-May-2006 01:46
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.
16-Apr-2006 05:10
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.
01-Apr-2006 12:54
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.
13-Dec-2005 09:41
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.
30-Sep-2005 02:55
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
foreach ( $arr as $key => &$value )
{
$value = 1;
}
// without next line you can get bad results...
//unset( $value );
$value = 159;
?>
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
foreach ( $arr as $key => $value )
{
$arr[ $key ] = 1;
}
?>
27-Sep-2005 01:53
Regarding the previous comment, thw following code does the job:
<?php
foreach($arr as $key => &$value) {
$value = 1;
}
?>
19-Sep-2005 06:14
Regarding the previous comment, the fact that this code has no effect is perfectly expected:
<?php
foreach($arr as $value) {
$value = 1;
}
?>
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
foreach($arr as $key => $value) {
$arr[$key] = 1;
}
?>
28-Aug-2005 02:28
[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 = array( "a" => 0, "b" => 1 );
$a2 = array( "aa" => 00, "bb" => 11 );
$together = array( $a1, $a2 );
foreach( $together as $single ) {
&