note 89587 added to function.strcmp

From: Date: Sun, 15 Mar 2009 10:36:41 +0000
Subject: note 89587 added to function.strcmp
Groups: php.notes 
Request: Send a blank email to php-notes+get-151961@lists.php.net to get a copy of this message
For those that are confused about the way this function works: <?php $str1 = 'a'; $str2 = 'b'; var_dump(strcmp($str1, $str2)); //int(-1) ?> Alphabetically 'a' precedes 'b'. If we view the strings as values 'a' is less than 'b' and therefore the function returns -1. If we were searching through an alphabetically sorted list we'd have a numerical index ($i) and compare the search string ($sstr) against each member of the string list ($slist), using strcmp we can check whether to go "up"($i++) or "down"($i--) through this list. Here's the example function: <?php function strInList ($sstr) { $slist = array('a', 'b', 'c', 'd', 'e' /* etc */); $i = sizeof($slist) / 2; //start the index in the middle while ($i < sizeof($slist) && $i >= 0) { //constrain $i to the scope of $slist $cmp = strcmp($slist[$i], $sstr); if ($cmp > 0) { //alphabetically, $slist[$i] procedes $sstr $i--; //move DOWN the list } else if ($cmp < 0) { //alphabetically, $slist[$i] precedes $sstr $i++; //move UP the list } else if ($cmp == 0) { //$slist[$i] occurs neither before nor after $sstr return true; //successful match } } return false; //The index fell out of the list scope, with no match made } ?> ---- Server IP: 117.104.160.194 Probable Submitter: 124.185.125.211 ---- Manual Page -- http://www.php.net/manual/en/function.strcmp.php Edit -- https://master.php.net/note/edit/89587 Del: integrated -- https://master.php.net/note/delete/89587/integrated Del: useless -- https://master.php.net/note/delete/89587/useless Del: bad code -- https://master.php.net/note/delete/89587/bad+code Del: spam -- https://master.php.net/note/delete/89587/spam Del: non-english -- https://master.php.net/note/delete/89587/non-english Del: in docs -- https://master.php.net/note/delete/89587/in+docs Del: other reasons-- https://master.php.net/note/delete/89587 Reject -- https://master.php.net/note/reject/89587 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#151961) next »