All entries tagged "dc:language=en".

« newer Page 2 of 12 older »

Algorithmic Advent: 03 – Addressing a multi-dimensional array index by string

This function might come in handy when loading settings from a configuration file.

/**
 * Sets a field of a multi-dimensional array by specifying the key in a
 * flat string format
 *
 * Usage example:
 *
 *   $demo = array();
 *   arraySetByFlatKey($demo, 'this.is.a.test', 'Hello World!');
 *   arraySetByFlatKey($demo, 'this.is.a.monster', 'Brwaaa!');
 *
 * Sets:
 *
 *   $demo['this']['is']['a']['test'] = 'Hello World!';
 *   $demo['this']['is']['a']['monster'] = 'Brwaaa!';
 *
 * @param array $a Array to set the index of
 * @param string $key Flat key representation
 * @param mixed $value Value to set the index to
 */
function arraySetByFlatKey(array &$a, $key, $value, $delimiter = '.')
{
    $keyParts = explode($delimiter, $key);
    $leaveKey = array_pop($keyParts);

    $parent = &$a;

    foreach ($keyParts as $part) {
        if (!isset($parent[$part])) {
            $parent[$part] = array();
        }

        $parent = &$parent[$part];
    }

    $parent[$leaveKey] = $value;
}

Dec 3 2010 • by Marc Ermshaus • type=post language=en php algorithmicadvent0 comments

Algorithmic Advent: 02 – Longest intersection of two strings

Hint: If no support for varying character lengths is needed (e. g. when not working with UTF-8), the mb_* function calls should be replaced with their non-multibyte pendants. Especially mb_strpos is very inefficient when used in loops.

/**
 * Returns the longest intersection of two strings
 *
 * Usage example:
 *
 *   $a = 'This is a wonderful test string.';
 *   $b = 'This is another wonderful string.';
 *   var_dump(getLongestIntersection($a, $b)); // string(11) " wonderful "
 * 
 * @param string $haystack First string
 * @param string $needle Second string
 * @return string Longest intersection of both strings
 */
function getLongestIntersection($haystack, $needle)
{
    // Length of needle string
    $nLen      = mb_strlen($needle);

    // Starting point (in needle) of longest matching substring
    $maxAnchor = 0;

    // Length of (so far) longest matching substring
    $maxLen    = 0;

    // Starting point (in needle) of current substring to test
    $sAnchor   = 0;

    // Length of current substring to test
    $sLen      = 0;

    // Do checks until either substring anchor runs out of needle string or
    // until there is no room left for a longer match
    while ($sAnchor < $nLen
        && $sAnchor + $sLen <= $nLen
    ) {
        // Increase substring length
        $sLen++;

        if (mb_strpos($haystack,
                      mb_substr($needle, $sAnchor, $sLen)) !== false
        ) {
            /* Substring found. A new match is always the longest match */

            $maxLen    = $sLen;
            $maxAnchor = $sAnchor;
        } else {
            /* Substring not found */

            // Shift anchor one position to the right
            $sAnchor++;

            // Don't bother looking for substrings shorter than current best
            // match. This makes sure that a new match is always the longest
            // match up to this point
            $sLen--;
        }
    }

    return mb_substr($needle, $maxAnchor, $maxLen);
}

Dec 2 2010 • by Marc Ermshaus • language=en php type=link algorithmicadvent0 comments

Algorithmic Advent: 01 – Weighted picks

This is the first entry of a small advent calendar series featuring PHP snippets. Hopefully one or two of them will be useful to anyone.

Today, we start with a function to pick a random entry from a weighted array.

/**
 * Picks an element from a weighted array
 *
 * @param  array $map "Element to weight factor" mappings (<mixed> => <int>)
 * @return mixed|null Picked element or null if empty array
 */
function pick(array $map)
{
    $sum  = array_sum($map);
    $rand = mt_rand(0, $sum - 1);
    $k    = 0;
    $pick = null;

    foreach ($map as $element => $weight) {
        $k += $weight;
        if ($rand < $k) {
            $pick = $element;
            break;
        }
    }

    return $pick;
}

This example will return „c“ in 60 % of the time, „b“ in 30 % and „a“ in 10 %.

$weights = array(
     'a' => 10,
     'b' => 30,
     'c' => 60,
);

for ($i = 0; $i < 50; $i++) {
    echo pick($weights) . ", ";
}

This example simulates the rolling of two 6-sided dice (2d6).

$twoDice = array(
     '2' => 1,
     '3' => 2,
     '4' => 3,
     '5' => 4,
     '6' => 5,
     '7' => 6,
     '8' => 5,
     '9' => 4,
    '10' => 3,
    '11' => 2,
    '12' => 1
);

$results = array();

for ($i = 0; $i < 100; $i++) {
    $pick =  pick($twoDice);
    $results[$pick] .= '*';
}

ksort($results);

foreach ($results as $pick => $amount) {
    echo $pick . ': ' . $amount . '<br />';
}

Dec 1 2010 • by Marc Ermshaus • language=en php type=link algorithmicadvent0 comments

Scalar type hints in upcoming PHP version?

Sebastian Bergmann writes that PHP 5.3.99 (which might be released as PHP 5.4) will introduce type hinting for scalar data types (e. g. function f(int $i, string $s) {}).

There is one thing to note: It seems like there are no plans to check or enforce the new type hints in the interpreter, so this feature might be purely syntactical. I am not sure whether this makes a lot of sense to me.

Nov 25 2010 • by Marc Ermshaus • language=en php type=link0 comments

PHP Snippet: Get all permutations

<?php

/**
 * Returns all possible permutations of $values containing $n elements using a
 * "draw and place back" algorithm
 *
 * The resulting array will always have pow(count($values), $n) entries.
 *
 * For
 *   $values = array('a', 'b') and $n = 2,
 * the result will contain:
 *   [aa, ab, ba, bb]
 *
 * @param array $values Vector to generate permutations of
 * @param int $n Elements per permutation
 * @return array Possible permutations
 */
function getPermutations(array $values, $n)
{
    $rec = function (array $values, &$ret, $n, array $cur = array()) use (&$rec)
    {
        if ($n > 0) {
            foreach ($values as $v) {
                $newCur = $cur;
                $newCur[] = $v;
                $rec($values, $ret, $n - 1, $newCur);
            }
        } else {
            $ret[] = $cur;
        }
    };

    $ret = array();
    $rec($values, $ret, $n);

    return $ret;
}



$values = range('a', 'd');
$n = 2;

$ret = getPermutations($values, $n);

foreach ($ret as $r) {
    foreach ($r as $d) {
        echo $d;
    }
    echo '<br>';
}

Nov 18 2010 • by Marc Ermshaus • type=post language=en php0 comments

PHP Template Attribute Language

PHPTAL is a template language that might actually be worth using. From the website:

To be short, PHPTAL is a XML/XHTML template library for PHP.

While most web developpers continue to use ASP/JSP/PHP tags as the core language of their templates, the Zope community came with a refreshing idea named TAL. The idea was to move presentation actions inside XHTML attributes instead of using plain tags or elements.

Nov 17 2010 • by Marc Ermshaus • language=en php type=link0 comments

Installing the Zend Framework into the document root

The Zend Framework's default directory layout assumes that you are able to place all of your library and application code outside of the web server's document root directory. In shared hosting environments, this is often impossible because the document root is the topmost directory you have access to.

Lorenzo Alberton explains how to setup the framework under these conditions.

Nov 1 2010 • by Marc Ermshaus • language=en php type=link0 comments