Will Fris's WordPress Weblog











{20150810}   array_sprintf

Do you know of a quicker way to do this?
I’d be glad to know so 🙂

The following code does a sprintf on a collection.


	if ( !function_exists( 'array_sprintf' ) ) {
		function array_sprintf ( $templateString , $inputArray ) {
			reset( $inputArray );
			while ( $i = each( $inputArray ) ) {
				if ( !is_array( $i[ 'value' ] ) ) {
					$i[ 'value' ] = array( $i[ 'value' ] );
				}
				array_unshift( $templateString , $i[ 'value' ] );
				$inputArray[ $i[ 'key' ] ] = call_user_func_array(
					'sprintf'
					, $i[ 'value' ]
				);
			}
			return $inputArray;
		}
	}

Obligatory example:


	$tags = array(
		array( 'href' => 'https://willfris.wordpress.com/' , 'txt' => 'This blog' )
		, [ 'http://willfris.nl/' , 'A site' ] # shorthand array-syntax
	);
	$element = [ '<li>' , '</li>' ];
	echo '<ul>' . $element[ 0 ]
		. implode(
			implode( $element )
			, array_sprintf( '<a href="%s">%s</a>' , $tags )
		)
		. $element[ 1 ] . '</ul>';


{20150724}   php’s nl2br is evil

Line-breaks <br /> are something for poetry and stuff.
Use paragraphs <p />.
They make up a <section /> or <article />.


if ( !function_exists( 'nl2p' ) ) {
    function nl2p ( $text ) {
        $peed = ''
            . '<p>'
            . str_replace(
                  array( "\r\n" , "\r" , "\n" )
                , '</p><p>'
                , $text
            )
            . '</p>'
        ;
        return $peed;
    }
}


{20110910}   getters, setters

één functienaam voor beide zaken

functionaliteit wordt bepaald aan de hand van invoer

mogelijke wijzen van invoer:

  1. geen invoer, ergo: getter

    mogelijke teruggave’s:

    • altijd een array in geval van samengestelde gegevens
    • altijd een single value van een specifiek datatype bij enkel gegeven
    • eventueel NULL
  2. invoer, ergo: setter

    • enkele invoer( één gegeven parameter)

      • setter is voor samengestelde gegevens
        1. enkele invoer is array

          verschillende invoeren worden nieuwe waarden van gegevens tenzij waarde van invoer gelijk is aan NULL

          over het algemeen zal/zullen hierbij de oude waarde/-n behouden blijven

        2. enkele invoer is geen array en geen NULL

          enkele invoer wordt de nieuwe waarde van de betreffende eigenschap

          over het algemeen zal/zullen hierbij de oude waarde/-n behouden blijven

      • setter is voor enkel gegeven

        invoer wordt nieuwe waarde voor gegeven

    • meerdere invoer( meer dan één meegegeven parameter)

      • setter is voor samengestelde gegevens

        verschillende invoeren worden de nieuwe waarden van gegevens tenzij de waarde van de invoer gelijk is aan NULL

        over het algemeen zal/zullen hierbij de oude waarde/-n behouden blijven

      • setter is voor een enkel gegeven

        màg niet voorkomen, dus een foutmelding/exception.



While working in PHP today, I wanted to have a way to turn a string like:
name=value,name=,name=value
(maybe even: name=value,name,name=value,=value,name=value )
I tried:
explode('=' , explode(',' , $array));
But unfortunately that did not work, since explode() does not except an array as argument. (And the small fact that I got the parameters mixed up first time around did not help either. 🙂 )

I could not immediately come up with a way to do this, so I searched for something like: `php recursive explode`.
Among others, I found `PHP split or explode`.
One of the questions that poster asks is: “Is it recommended to avoid to use the split() function and other PHP functions ?”
To answer this, I went to the php split-function page in the manual, which I can do by typing: `p split` in the location bar since I use firefox and made `p` the keyword for this search engine.
(I actually type: `:o p split`, since I am using the vimperator add-on for firefox, maybe more about that some other time though.)

Nonetheless, that page did not answer my question either.
I however digressed as I do very often, going off to write this blog-entry and to answer my new question:
What is the difference between str_split and explode ?
Well , in short to this is:

str_split
splits a string by a certain amount of chars and returns an array

while

explode
splits a string by a certain other string and returns an array

.
This however did not solve the problem , so I searched a bit more: `explode to associative array` .
Which gave me some useful hits that were good for hints, but did not provide a way to do key-value_pairs.

I thought it took too long to find a solution, so I wrote my own, in the neglect of it being an `unelegant` solution.
So for now, this is my solution to the problem:


<?php
#I have absolutely no idea why explode() should have it's delimiter as first parameter(as it says in the manual).
function splita ($string , $delimiters = ' ')
	{
		$array                                      =  array();
		is_array($delimiters) ? NULL : $delimiters  =  array_slice(func_get_args() , 1);//Check if array is empty?
		if (count($delimiters) !== 2){throw new Exception('Sorry, not yet supported.');}
		reset($delimiters);
		$arr                                        =  explode(current($delimiters) , $string);
		next($delimiters);
		foreach ($arr as $index => $name_value_pair)
			{
				$tmp  =  explode(current($delimiters) , $name_value_pair);
				if ($tmp === FALSE)
					{//echo 'geen value:' . implode(':',$tmp);
						$array[$tmp[0]]  =  '';
					}
				elseif (isset($tmp[1]))
					{//echo 'name-value:' . implode(':',$tmp);
						$array[$tmp[0]]  =  $tmp[1];
					}
				else
					{//echo 'just-value:' . implode(':',$tmp);
						$array[]         =  $tmp[0];
					}
			}
		return $array;
	}
?>

I will probably change it again sometime, there’s also stuff I did not take into account yet.
Anyway, for now, it will do.

Update (Sun 2009-08-23, 15:55.47 CEST):
I knew it…
The parse_str() function… doh!



{20090806}   MySQL – Grant

So I forgot about the `backtics` again … :S


http://dev.mysql.com/doc/refman/5.1/en/grant.html

To specify quoted values, quote database, table, column, and routine names as identifiers, using backticks (“`”). Quote user names and host names as identifiers or as strings, using either backticks (“`”), single quotes (“’”), or double quotes (“””). Quote passwords as strings, using single quotes.

The “_” and “%” wildcards are allowed when specifying database names in GRANT statements that grant privileges at the global or database levels. This means, for example, that if you want to use a “_” character as part of a database name, you should specify it as “\_” in the GRANT statement, to prevent the user from being able to access additional databases matching the wildcard pattern; for example, GRANT … ON `foo\_bar`.* TO ….



When you are developing a page and use firebug stuff inside your script, you might find that in other browsers your javascript does not get executed.

You could include the external javascript file to enable firebug inside other browsers. This can be done since firebug is written out with javascript, isn’t that nice?
Instructions can be found on firebug’s website.

Another option is to provide fake-functions||methods||thingies||whatever that will capture the firebug-calls from your script and do nothing at all besides that.

As demonstrated in many places, for instance:
http://davidwalsh.name/how-to-sniff-firebug-disable
http://groups.google.com/group/firebug/browse_thread/thread/bbc984b3e075fbbe
http://www.pqpq.de/mt/2008/07/firebug-debugging.html

However, it didn’t work here. (
Ubuntu 8.04 i.e. Hardy Heron
FireFox 3. 0.3(a.t.m.)
FireBug installed from the Ubuntu repostiories
)

So I fiddled somewhat:
if (window.console){
  for (index in window.console){
    console.log(index + ' >' + window.console[index]);
  }
}

This gives me everything of window.console if I am not mistaken.

Long story short, no window.console.firebug || console.firebug
.
So I decided to do a check for something else, namely firebugVersion()
.
Which give me this script:

if (!window.console || !window.console.firebugVersion)
{
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
  window.console = {};
  for (i in names)
  {
    window.console[names[i]] = function() {};
  }
}

This works for me,
not giving me errors in Opera
and giving me console-stuff in firefox.



I have adapted hixie‘s solution to embed flash movies.
Although Roberto Scano‘s method seems to be the same, it is somewhat different.
In the browser on my platform Roberto’s method shows me two alternative messages, which I find excessive.
I also came across Jason Gill‘s method, a version quite like hixie’s though not hixie’s, Jason says.

I like Hixie and Gill their approaches. What I do not understand though, is Read the rest of this entry »



{20080422}   quicker then innerHTML

In this article a method is described which is supposed to be quicker then javascript’s innerHTML and also the DOM-way, it’s a combination of both of those.



To make some comparison between CodeIgniter, CI from here on, and Symfony Framework, SF from here on, I decided to go through some of the first hits of Google for a change.

In general I can read in most posts that:
Both of the frameworks have superb documentation, which is very nice, thumbs up!

CI is nice and lightweight, while SF is nice and heavyweight
which just makes CI more responsive then SF
SF is all about best practises whereas CI seems to take a more pragmatic route
SF is in php5, CI can be in php4 _and_ php5
SF is mainly meant for big ass applications because of the way it is set up with a cli to create applications, modules, and what not more, while CI is more meant to be a great library with an easy to understand setup

I also read that CI has gotten a fork called Kohana a all php5-strict framework.
I will most certainly use this framework in a future project to get the feel of it.

I’ve started using Symfony now;
I wanted to have a InnoDB table (dunno why. :P) and I wanted it to be in utf8 charset and utf8_bin collation (dunno why. :S)
I found my InnoDB info here:
http://www.symfony-framework.com/2007/10/18/mysql-connection-configuration-schema-and-model-generation/
And the utf8 stuff can be found in chapter 8 of the symfony manual/book/or whatever.



et cetera