Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 59
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Po wysłaniu do Dariusza problemu jeszcze nie opisanego w poradach, odpowiedź pojawia się na stronach już po 24 godzinach. To jedna z najważniejszych zalet serwisu! Za około 100 złotych rocznie mam profesjonalnego i doświadczonego konsultanta od technologii internetowych! Polecam serwis z poradami każdemu webmasterowi, niezależnie od stażu pracy i umiejętności.

Paweł Kowalski
grupa hiperMEDIA.pl

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

strcmp

(PHP 3, PHP 4, PHP 5)

strcmp -- Binary safe string comparison

Description

int strcmp ( string str1, string str2 )

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), and strstr().




User Contributed Notes

francis at flourish dot org
08-Dec-2005 03:57

If you want to strings according to locale, use strcoll instead.


element @ no spam dot net
20-Feb-2005 12:42

When using strcmp to compare results received from a form, keep in mind that the way you decide to encapsulate the value of the form will have an effect on your strcmp() results.

Example:

<input type="post" name="user[0]" value="abc">
<input type="post" name="user[1]" value='abc'>

strcmp() will not return the values sent from this form as "0".

However, by using single-quotes or double-quotes to encapsulate BOTH values, strcmp() will return a "0" result.


S dot Radovanovic at TriMM dot nl
07-Feb-2005 03:36

One thing to note in comparison with ==

When we make a comparison with == php automaticly converts strings to integers when either side of the comparison is an integer, f.e.:
<?
$value
= 0;
if(
$value == "submit") {
   echo
"Let's submit";
}
?>
Above would be succesful, since "submit" is converted to an integer (eq 0) and the equation is would return true; (that's why (1 == "1submit") would also return true)

That's why we should use strcmp or === (checks type also), for string comparisons.

So my conclusion is that when comparing string, you'd better not make use of == (use strmp or === instead). For integer comparisons the == equation can be usefull, since our values will always be casted to an integer (1 == "1" returns true).


x123 at bestof-inter dot net
30-Oct-2004 03:43

Please tell what you mean by "alphabetically" and when you say
"because of the way it works, it is not very useful..." or
"I get strange results, 1 for strings that are equal, etc." :
give an example where it does not work and/or show where your script works better!
(To test some PHP code, it is sufficient to have a file of 3 lines:
<form action='' method=POST><input type=submit value=Evaluate>
<textarea id=c><?=$c=stripslashes($_POST['c'])?></textarea>
<br>Result of the above:<pre><?=eval($c)?></pre></form>)

Imagine how much time is lost for visitors trying to figure out what your program does differently from strcmp ?

Imagine how much resources are wasted if PHP users are made to think that PHP functions don't work well and use the EXTREMELY inefficient routines proposed below (e.g. a string comparision routine that uses substr(...,$i,1) to access individual caracters...!)

If the documentation says 'binary safe' this should mean that strings are compared byte by byte (according to internal format)
- if strcmp() does instead use locale collation tables, this should be clearly mentioned in the documentation.


pabloATnkstudiosDOTnet
01-Jun-2004 08:36

Just note that the documentation about the function returns is a little confused.

So...

If $str1 == $str2 strcmp return 0.
If $str1  > $str2 strcmp return 1.
If $str1  < $str2 strcmp return -1.

Pablo Rosciani
http://pablo.rosciani.com.ar


jcanals at totsoft dot com
31-Jan-2004 03:05

Some notes about the spanish locale. I've read some notes that says  "CH", "RR" or "LL" must be considered as a single letter in Spanish. That's not really tru. "CH", "RR" and "LL" where considered a single letter in the past (lot of years ago), for that you must use the "Tradictional Sort". Nowadays, the Academy uses the Modern Sort and recomends not to consider anymore "CH", "RR" and "LL" as a single letter. They must be considered two separated letters and sort and compare on that way.

Ju just have to take a look to the Offial Spanish Language Dictionary and you can see there that from many years ago there is not the separated section for "CH", "LL" or "RR" ... i.e. words starting with CH must be after the ones starting by CG, and before the ones starting by CI.


gregd at sad dot net
08-Sep-2003 08:49

In cases when you need to compare a line from a just parsed file stream to match a user-defined "nametag" (useful for parsing ini and configuration files), keep in mind the 'end of line' tags as well:

// nametag to look for in a file (notice a required "\r\n" at the end)
$nametag = "[System]\r\n";

// ...assuming the file has been aready opened for reading and the stream is bound to $filehandle... parse the file until an EOF or $nametag encountered.

while (!feof ($handle))
{
   $buffer = fgets($filehandle);
   if (strcmp($nametag, $buffer) == 0)
   {
       // at this point "[System]" is found, do additional parsings...
       break;
   }
}


admin[nospam] at pretend dot tk
18-Jun-2003 04:44

Reguarding the above note on language specific string comparisons, LL and RR are also single letters in the Spanish language.


mnunemacher at datility dot net
28-Apr-2003 12:40

Because of the way this function works, it's not very useful for ordering strings alphabetically. If you're trying to alphabetize a list of strings (like a dictionary does), you may want to use the following functions instead:
-----------------

// Returns 1 if $str1 comes before $str2 alphabetically
// Returns -1 if $str1 comes after $str2 alphabetically
// Returns 0 if $str1 and $str2 are the same
function orderAlpha ( $str1, $str2 ) {
   $limit = null;

   if ( strlen( $str1 ) > strlen( $str2 ) ) {
     $limit  = strlen( $str2 );
   } else {
     $limit = strlen( $str1 );
   }

   for ( $i = 0;$i < $limit;$i++ ) {
     if ( substr( $str1, $i, 1 ) > substr( $str2, $i, 1 ) ) {
         return 1;
     } else if ( substr( $str1, $i, 1 ) < substr( $str2, $i, 1 ) ) {
         return -1;
     }
   }

   if ( strlen( $str1 ) > strlen( $str2 ) ) {
     return 1;
   } else if ( strlen( $str1 ) < strlen( $str2 ) ) {
     return -1;
   }

   return 0;
}

// Case insensitive version of orderAlpha
function orderiAlpha ( $str1, $str2 ) {
   return orderAlpha( strtolower( $str1 ), strtolower( $str2 ) );
}
-----------------


ahmed at somantic dot net
23-Mar-2003 09:52

For some reason the strcmp fails for this function if the $item_to_compare->ID = "AB123" or some similar string. This happened even though $ID = "AB123":
<pre>

function item_exists($ID)
{
   // returns 0 for error
   global $item_list; // this is an array of class objects

   if (is_array($item_list))
   {
     foreach ($item_list as $key => $item_to_compare)
     {
         if (!strcmp($item_to_compare->ID, $ID))
         {
           unset ($item_list);
           return $key;
         }
     }
   }
   // Else fail
   unset ($item_list);
   return 0;
}

</pre>

So I was forced to do this:

<pre>

function item_exists($ID)
{
   // returns 0 for error
   global $item_list;

   if (is_array($item_list))
   {
     for($i = 0; $i < count($item_list); $i++)
     {
         if (!strcmp($item_list[$i]->ID, $ID))
         {
           unset ($item_list);
           return $i;
         }
     }
   }
   // Else fail
   unset ($item_list);
   return 0;
}

</pre>


izhan dot khalib at acpibhd dot com
17-Dec-2002 08:13

I have tried the  strcmp function. Pls be very carefull. The string comparison must exactly "equal". So many people had confused.

I.e

My program read a string from test.txt file to get the
"[company name]" string.

// get contents of a file into a string
$filename = "test.txt";
$fd = fopen ($filename, "rb");
$contents = fread ($fd, filesize ($filename));

for($i=0;$i<strpos($contents, "]")+1;$i++)
{
//print $contents[$i];
//$a=trim($contents[$i]);
$a=$contents[$i];
echo $a;
//echo $i;
}

$str2="[companyname]";

// this comparison will resulted on greater (1), $result=1
//please remember $tempvariable[2] != $tempvariable (is not equal)
$result = strcmp(strtolower($a),strtolower($str2));

//this comparison working properly, $result=0
//$result = strcmp(strtolower($a),strtolower($str2[12]));

echo $result;

if ($a==$str2[12]) //double check the equality of string
{
echo "read the NextLine"; }
 else {
 echo "not equal";
 }
//end

fclose ($fd);
?>

I hope the above example will help you.


madsen at sjovedyr dot dk
02-Oct-2002 08:59

It's definitely worth noting that the return-values of strcmp() when used for i.e. password-checking is the oposite of that of the ==-operator.

I.e.:
$pw1 = "yeah";
$pw2 = "yeah";

if (strcmp($pw1, $pw2)) {  // This returns false.
   // $pw1 and $pw2 are NOT the same.
} else {
   // $pw1 and $pw2 are the same.
}

Where the use of the == operator would give us.:
if ($pw1==$pw2) {    // This returns true.
   // $pw1 and $pw2 are the same.
} else {
   // $pw1 and $pw2 are NOT the same.
}

Additionally, to check if $pw1 and $pw2 are of the same type you can use the === operator.


27-Aug-2002 03:45

In summary, strcmp() does not necessarily use the ASCII code order of each character like in the 'C' locale, but instead parse each string to match language-specific character entities (such as 'ch' in Spanish, or 'dz' in Czech), whose collation order is then compared. When both character entities have the same collation order (such as 'ss' and '

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt