Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

indexOf an array element

Finds the first instance of an element ($needle) in an array ($haystack). It works in ascending order (from element 0 to the array's length), can be easily modified to work in reverse if required. Will return either the index of the first occurance of false if hasn't been found.

function indexOf($needle, $haystack) {                // conversion of JavaScripts most awesome
        for ($i=0;$i<count($haystack);$i++) {         // indexOf function.  Searches an array for
                if ($haystack[$i] == $needle) {       // a value and returns the index of the *first*
                        return $i;                    // occurance
                }
        }
        return false;
}

Integer to alphanumeric character

A function that converts an integer between 0 and 61 into an alphanumberic character. Ranges from 0-9, A-Z, a-z. Very handy for generating random strings and stuff like that.

function map_char($num) { 
   $int = $num; $int+=48;
   ($int > 57) ? $int += 7 : null;
   ($int > 90) ? $int += 6 : null;
   return chr($int);
}

Reverse switch

Handy technique if you want to use more complex comparisons other than == in a switch statement. Much tidier than the elseif equivilant.
switch(true) {

   case $x == "hello":
      // $x is hello

   case is_numeric($x):
      // $x is a number

   case $x < 10:
      // $x is less than 10
}

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS