I ran the following experiment to compare arrays.
1 st - using (substr($key,0,5 == "HTTP_") & 2 nd - using (!strncmp($key, 'HTTP_', 5))
I wanted to work out the fastest way to get the first few characters from a array
BENCHMARK ITERATION RESULT IS:
if (substr($key,0,5 == "HTTP_").... - 0,000481s
if (!strncmp($key, 'HTTP_', 5)).... - 0,000405s
strncmp() is 20% faster than substr() :D
<?php
// SAMPLE FUNCTION
function strncmp_match($arr)
{
foreach ($arr as $key => $val)
{
//if (substr($key,0,5 == "HTTP_")
if (!strncmp($key, 'HTTP_', 5))
{
$out[$key] = $val;
}
}
return $out;
}
// EXAMPLE USE
?><pre><?php
print_r(strncmp_match($_SERVER));
?></pre>
will display code like this:
Array
(
[HTTP_ACCEPT] => XXX
[HTTP_ACCEPT_LANGUAGE] => pl
[HTTP_UA_CPU] => x64
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_USER_AGENT] => Mozilla/4.0
(compatible; MSIE 7.0;
Windows NT 5.1;
.NET CLR 1.1.4322;
.NET CLR 2.0.50727)
[HTTP_HOST] => XXX.XXX.XXX.XXX
[HTTP_CONNECTION] => Keep-Alive
[HTTP_COOKIE] => __utma=XX;__utmz=XX.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
)
strncmp
(PHP 4, PHP 5)
strncmp — 처음 n 문자의 바이너리 안전 문자열 비교
설명
int strncmp
( string $str1
, string $str2
, int $len
)
이 함수는 비교에 사용하는 각 문자열에 (최대 제한) 비교에 사용할 문자 수를 지정할 수 있는 점을 제외하면, strcmp()와 동일합니다.
이 비교는 대소문자를 구분합니다.
인수
- str1
-
첫번째 문자열.
- str2
-
두번째 문자열.
- len
-
비교에 사용할 문자열의 길이.
반환값
str1 이 str2 보다 작으면 < 0을; str1 이 str2 보다 크면 > 0을, 같으면 0을 반환합니다.
참고
- preg_match() - 정규표현식 매치를 수행
- strcmp() - 바이너리 안전 문자열 비교
- strcasecmp() - 대소문자 구분 없는 바이너리 안전 문자열 비교
- substr() - Return part of a string
- stristr() - 대소문자를 구분하지 않는 strstr
- strncasecmp() - 대소문자 구분 없는 처음 n 문자의 바이너리 안전 문자열 비교
- strstr() - 문자열이 처음으로 나오는 부분을 찾습니다
strncmp
codeguru at crazyprogrammer dot cba dot pl
24-Jan-2008 07:07
24-Jan-2008 07:07
Anonymous
17-Apr-2002 11:46
17-Apr-2002 11:46
strncmp("sample","sam",4) returns 1 because the final requirement is if one string terminates before len, then the other must also terminate at that position.
You can imagine that all your strings have one more final, invisible "termination" character. If that termination character happens to be within in len, then it must match, too.
For instance, write that termination character with, say, the sequence "\0". Then you can equivalently consider that function call as strncmp("sample\0","sam\0",4).
So, the "p" in "sample" does not match the termination character in "sam".
