Friday Algorithms: Quicksort – Difference Between PHP and JavaScript

Here’s some Friday fun. Let me show you one sorting algorithm, perhaps the most known of all them – the quick sort, implemented both on PHP and JavaScript. Although the code look similar between both languages, there are few differences, that show the importance of the syntax knowledge!

1. PHP

<?php
 
    $unsorted = array(2,4,5,63,4,5,63,2,4,43);
 
    function quicksort($array)
    {
        if (count($array) == 0)
            return array();
 
        $pivot = $array[0];
        $left = $right = array();
 
        for ($i = 1; $i < count($array); $i++) {
            if ($array[$i] < $pivot)
                $left[] = $array[$i];
            else
                $right[] = $array[$i];
        }
 
        return array_merge(quicksort($left), array($pivot), quicksort($right));
    }
 
    $sorted = quicksort($unsorted);
 
    print_r($sorted);

2. JavaScript

var a = [2,4,5,63,4,5,63,2,4,43];
 
function quicksort(arr)
{
    if (arr.length == 0)
        return [];
 
    var left = new Array();
    var right = new Array();
    var pivot = arr[0];
 
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] < pivot) {
           left.push(arr[i]);
        } else {
           right.push(arr[i]);
        }
    }
 
    return quicksort(left).concat(pivot, quicksort(right));
}
 
console.log(quicksort(a));

Note that the first conditional statement is quite important! While in PHP the count function will return 0 either on a NULL value or an empty array and you can substitute it with something like count($array) < 2

if (count($array) < 2)
	return $array;

in JavaScript you cannot use that because of the presence of the ‘undefined’ value when an “empty” array is passed as an argument. Thus you’ve the conditional above:

// this will result with an error
if (arr.length < 2)
        return arr;

Coming Up Next …

An iterative version of the algorithm next Friday!

JSON and Zend Framework? – Zend_Json

That’s really a good Zend Framework’s class that help you do the encode/decode job very easily. First of all it escapes everything for you and second it prints a correct/valid code. Note that sometimes if you have a trailing whitespace after the closing PHP tag – ?> that will result in an error.

Here’s some code:

public function jsonAction()
{
	$data = array(3,4,'test', 'my-name' => 3,4);
 
	echo Zend_Json::encode($data);
 
	$this->_helper->viewRenderer->setNoRender(true);
	$this->view->layout()->disableLayout();
}

and the result is:

{"0":3,"1":4,"2":"test","my-name":3,"3":4}

Note that all integers are printed without double quotes – which saves some space!

Flowplayer and Captions (Subtitles)

Actually I couldn’t mange to make it work with a non-javascript approach, but however with the .js help it works. I’ll paste here this code, hopefully this will help.

Note that you’ve to change plugins/javascripts/videos/captions path!

<html>
<body>
<div id="player" style="width:480px;height:360px"></div>
<script src="Flowplayer.Captions/flowplayer-3.2.2.min.js"></script>
<script>
 
$f("player", "Flowplayer.Captions/flowplayer-3.1.5.swf", {
    clip : {
        url : "Flowplayer.Captions/bach.flv",
        captionUrl : 'Flowplayer.Captions/bachen.srt'
    },
    plugins:  {
        captions: {
            url: 'Flowplayer.Captions/flowplayer.captions-3.2.1.swf',
            captionTarget: 'content'
        },
        content: {
            url : 'Flowplayer.Captions/flowplayer.content-3.2.0.swf',
            bottom: 5,
            height: 50,
            backgroundColor: 'transparent',
            backgroundGradient: 'none',
            border: 0,
            textDecoration: 'outline',
            style: {
                body: {
                    fontSize: 15,
                    fontFamily: 'Arial',
                    textAlign: 'center',
                    color: '#ffffff'
                }
            }
        },
        controls: {
            url : 'Flowplayer.Captions/flowplayer.controls-3.1.5.swf'
        }
    }
});
 
setTimeout(function() {
    $f('player').getPlugin('captions').loadCaptions(0, 'Flowplayer.Captions/bachbg.srt');
}, 3000);
 
</script>
</body>
</html>

Bind Zend Action with Non-Default View

Action – View

You may know that every controller’s action in Zend Framework has to be bind to a view. Normally you can disable the view for a specific action, but how about “forking” an action to render different views?!

In example when some _GET parameter is set redirect to another view? That’s rather strange and perhaps there’s a clear and yet full MVC solution! First of all you can setup all of the view variables simply in the “parent” action.

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$this->view->title = 'This is the default action!';	
	}
}

Than the view file will contain something like:

// index/index.phtml
<h1><?php echo $this->title ?></h1>

Than whenever you have the given _GET set you can _forward to another action (perhaps with no code at all) and only a different view. Thus you don’t setup twice the view variables.

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$this->view->title = 'This is the default action!';	
 
		if (isset($_GET['my_param'])) {
			$this->_forward('another');
		}
	}
 
	public function anotherAction()
	{}
}

And there are two views practically for one action:

// index/index.phtml
<h1><?php echo $this->title ?></h1>
 
// index/another.phtml
<h2><?php echo $this->title ?></h2>