BigToach.com

PHP Snippets

« 1 2

letterfy

Information

(PHP Version >= 4)
Functions used in this snippet: is_numeric, strlen, in_array, substr.

Description

str letterfy( int int )

Returns a [typestr[/type] suffix of either st, nd, rd, or th based on the last 1 or two digits of the supplied int

Snippet

<?php
function letterfy($int){
    if(!
is_numeric($int{strlen($int) - 1})) return;
    if(
in_array(substr($int,-2), array(11,12,13))) return 'th';
    switch(
$int{strlen($int) - 1}){
        case 
1: return 'st';
        case 
2: return 'nd';
        case 
3: return 'rd';
        default: return 
'th';
    }
}
?>

Example

letterfy Can be used in the following way:

<?php
$x 
10;
echo 
$x letterfy($x); // 10th

$x 1;
echo 
$x letterfy($x// 1st

$x 22;
echo 
$x letterfy($x// 22nd

$x 33;
echo 
$x letterfy($x// 33rd

$x 111;
echo 
$x letterfy($x// 111th


?>

Added on Aug 10th at 7 am by Scott - 0 Comments


array_sum_assoc

Information

(PHP Version >= 3)
Functions used in this snippet: is_array, sizeof, array_sum_assoc.

Description

int array_sum_assoc( array array )

Sum's up all the values in the array array associatively.

Snippet

<?php
function array_sum_assoc($array){
    if(!
is_array($array) || sizeof($array) === 0){
        return 
false;
    }
    
$count 0;
    foreach(
$array as $key=>$value){
        if(
is_array($value)){
            
$count += array_sum_assoc($value);
        }else{
            
$count += $value;
        }
    }
    return 
$count;
}
?>

Example

array_sum_assoc Can be used in the following way:

<?php
// make an associative array
$array = array(1,array(1),array(1,array(1)));

echo 
array_sum_assoc($array);
// outputs 4, array_sum would output 1

?>

Added on Aug 9th at 7 pm by Scott - 0 Comments


avg

Information

(PHP Version >= 4.0.4)
Functions used in this snippet: is_array, sizeof, array_sum.

Description

int avg( array array )

Takes the array array and gives you the average of its values.

Snippet

<?php
function avg($array){
    if(
is_array($array) && sizeof($array) !== 0){
        return (
array_sum($array) / sizeof($array));
    }
    return 
false;
}
?>

Example

avg Can be used in the following way:

<?php
$array 
= array(1,3,4,9,41,5,87,6,62,4,8,6,8,7,5,6);

echo 
avg($array); // 16.375
?>

Added on Aug 8th at 5 am by Scott - 0 Comments


« 1 2