Creating a (autofocus) Polyfill

In the ever-changing world of browser topography, every so often there exists an expectation in the community that some feature or API will be available in a browser, and it’s not.

We have an approach to mitigating these types of issues though, and we call it polyfilling. To quote Remy Sharp, “A polyfill, or polyfiller, is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will.”

A question was recently asked on Stack Overflow about automatically applying focus to an input element when the page loads. The first responses suggested using a tool like jQuery to target the element, and invoke its focus method. While this works, it adds additional overhead in environments where it’s not needed.

My initial solution to the question was to use the autofocus boolean attribute on the input element of choice. Shortly after suggesting this, I realized this attribute was only introduced in Internet Explorer at version 10, meaning users of 6, 7, 8, and 9 wouldn’t get the behavior the developer expected – perfect opportunity to author a polyfill.

Our goal in building a solid polyfill is to not make its presence known; we want the web developer to author their markup as they would normally, while we quietly teach the browser to make sense of the unknown autofocus attribute.

So we start with basic HTML:

<input name="name" placeholder="John Doe" autofocus />

In browsers like Internet Explorer 10, Chrome 26, or Firefox 20, focus will be immediately given to this element upon page load. But for Internet Explorer 6-9 and versions of Firefox prior to 4.0, we’ll have to add a bit of assistance.

We start by first performing a feature-detect for the autofocus property in a freshly-created input element. In browsers that support this property, the default value is false:

// Proceed only if new inputs don't have the autofocus property
if ( document.createElement("input").autofocus === undefined ) {

}

This condition will only evaluate to true in browsers that don’t natively understand the autofocus attribute, and as such, this will be our sandbox to play in while constructing our polyfill. We’ll need to go through a few steps for this polyfill, so let’s have a look at what they are:

  1. Cycle over all forms
  2. Cycle over all elements in each form
  3. Check attributes of each element for autofocus
  4. If found, trigger focus, and break out of all loops (only one instance of autofocus should exist on in a document, otherwise you’ll get inconsistent cross-browser results)

Our first step in the above list is to cycle over all the forms. We can use the document.forms collection to find all of the forms on the document. We’ll also create a variable to track our index in the collection of forms. Lastly, we’ll add a label to this loop so that we can break from it later:

// Get a reference to all forms, and an index variable
var forms = document.forms, fIndex = -1;

// Begin cycling over all forms in the document
formloop: while ( ++fIndex < forms.length ) {

}

Next, within our formloop, we need to get a collection of the current form’s elements. Additionally, we will be creating another index variable to help us navigate this new collection:

// Get a reference to all elements in form, and an index variable
var elements = forms[ fIndex ].elements, eIndex = -1;

// Begin cycling over all elements in collection
while ( ++eIndex < elements.length ) {

}

The third step in our process is to check for the autofocus attribute in each element. There are various ways you can do this, and I explored several of them. For instance, you could use the hasAttribute method, but this is only supported in Internet Explorer from version 8 (meaning you’d have to polyfill it in earlier versions).

In the end I wound up checking for the attribute as a key in the element.attributes collection. If not present, the result will be falsey, and the loop will skip to the next element in the nodeList:

// Check for the autofocus attribute
if ( elements[ eIndex ].attributes["autofocus"] ) {

}

Finally, we arrive at our last step. We have found an element that has the attribute we’re looking for, and it’s time to focus on it, break out of the loops, and call it quits.

// If found, trigger focus
elements[ eIndex ].focus();

// And break out of outer loop
break formloop;

This is where the formloop label comes in handy; a simple break would have broken the element loop, but not the forms loop, meaning subsequent form elements (and their children) would be evaluated. Since only one instance of autofocus should appear in a document, this is not the behavior we want.

The final result is wrapped in an IIFE (Immediately Invoking Function Expression) which runs our code immediately, as well as prevents our variables from appearing in the global namespace, potentially causing harm to the rest of the document or application.

(function () {

    // Proceed only if new inputs don't have the autofocus property
    if ( document.createElement("input").autofocus === undefined ) {

        // Get a reference to all forms, and an index variable
        var forms = document.forms, fIndex = -1;

        // Begin cycling over all forms in the document
        formloop: while ( ++fIndex < forms.length ) {

            // Reference all elements in form, and an index variable
            var elements = forms[ fIndex ].elements, eIndex = -1;

            // Begin cycling over all elements in collection
            while ( ++eIndex < elements.length ) {

                // Check for the autofocus attribute
                if ( elements[ eIndex ].attributes["autofocus"] ) {

                    // If found, trigger focus
                    elements[ eIndex ].focus();

                    // And break out of outer loop
                    break formloop;

                }

            }

        }

    }

}());

There you have it, a polyfill that gives autofocus behavior to browsers that don’t natively support it. By dropping this in to your website, you can now carry on your merry way using great features of HTML like this, without worrying what negative effect it might have on your Internet Explorer 6, 7, 8, or even 9 visitors.

Phenomenal Day thanks to jQuery and Windows 8

Friday, March 29th, 2013, was a phenomenal day in this developer’s life.

In late 2012 my employer, appendTo, began working with Microsoft on an extremely exciting project – preparing a version of the web’s most beloved JavaScript library, jQuery, for Windows RT and use in Windows Store applications. This was particularly exciting for me since jQuery is one of my most active tags on Stack Overflow.

Towards the end of our work in preparing this special version of jQuery, I had the great pleasure of working with Elijah Manor on material that would be presented at //build/ 2012 by one of appendTo’s founders, Mike Hostetler.

We had successfully delivered a version of jQuery that worked with the new security model in Windows Store applications. But this wasn’t the end-goal; none of us wanted to maintain a clone of jQuery that was engineered specifically for Windows Store applications.

The project was a huge success, I was on cloud 9 having gotten to work with such phenomenal developers, and fantastic partners, on such a game-changing project. But again, our work wasn’t done – we merely wet our appetites for far better results. We wanted jQuery itself to work in Windows Store applications, not some sufficiently-similar clone of jQuery.

Our focus was then turned to working more closely with jQuery core contributors, which resulted in me getting to meet even more amazing people, like the President of the jQuery Foundation, Dave Methvin. Dave is one of those old-school hackers that could keep you tuned to his every word for hours on end; such an amazing guy. With guys like him at the helm, it’s easy to see why jQuery is such a success.

Moving forward, I began testing jQuery builds within Windows Store applications. This required forking, cloning, building, authoring and modifying unit tests, and more; it was a smörgåsbord of geek indulgence. At this time jQuery core contributors were working hard on version 2.0, the highly-anticipated version of jQuery that would shed itself of legacy support like a cicada liberated from it’s shell.

The timing couldn’t have been more perfect; Dave and the others were carefully extracting massive chunks of code from jQuery’s core that existed for no other reason than to support over a decade of antiquated browsers. In parallel to their efforts, appendTo was diving into versions of jQuery from 1.8.3 to pre-builds of 2.0, addressing any and all patterns considered “unsafe” in the new non-browser environment.

In the end, it all paid off. jQuery 2.0 appears to be ready for Windows Store applications, and every web-developer looking to try their hands in the lucrative market of Native Windows 8 applications authored in JavaScript (and now jQuery) has a familiar gateway into the new stomping grounds. It’s been an exciting project, and I’m incredibly humbled to have played a role in all of it.

jquery-pagesEverything peeked for me yesterday though, when co-worker Ralph Whitbeck and I had our article Building Windows Store Applications With jQuery 2.0 published on Nettuts+. Immediately following that, I was mentioned on the Interoperability @ Microsoft blog. And soon thereafter, mentioned on none other than TechCrunch, a site with over 1,600,000 tech-loving subscribers.

I imagine this type of thing happens everyday with various different developers. You put your nose down into a project that you are personally excited to be a part of. You work countless hours researching, writing, and testing. You meet a few exciting people along the way, and then one day you lift up your eyes to realize that you just had part in something truly amazing.

The web is such an exciting place, and contributing to open-source projects is an incredibly rewarding thing. Fortunately, for myself and all of my peers, getting your hands dirty with such amazing projects is easier today than it has ever been before thanks to services like GitHub.

As for me, I’m looking forward to seeing how jQuery 2.0 and beyond are used in Windows Store applications, and perhaps be so fortunate enough to contribute further to this amazing project in the future. You can do the same.

Taking the Internet Explorer Challenge

I’m going to use Internet Explorer 10 as my primary browser for one week. That’s one week without browsing, tweeting, or listening to turntable in Chrome (current “Browser of Choice”). That’s one week deep inside the bowels of the browser that burned me, and so many of my peers, so badly over the last decade. One week in the heart of the beast.

Why? Isn’t Internet Explorer supposed to be a thing of the past? A bad phase in the history of the web that we’re slowly recovering from? The faint image of the broken internet from yesterday, replaced by far more standards-compliant browsers like Firefox and Chrome? Well, yes, and no.

If I’m honest with myself, and everybody else, it’s not the browser that burned me. Internet Explorer dominated the market back in the day when I got excited to see 3kb/sec downloads. It was installed along side Netscape Navigator, but won me over pretty quickly.

The browser won a lot of people over, including corporations who went on to develop internal applications that depended on its implementation of HTML, CSS, and J(ava)Script. And then the world changed around them; around all of us.

Dial-up was becoming a thing of the past, and new browsers were creeping into the scene. Firefox rose like a phoenix from the ashes of Netscape, and then Google got into the game with Chrome. These later browsers took advantage of faster and more consistent connections and offered streamlined updates that happened silently in the background.

Internet Explorer was still dominating in the global market, but these antiquated versions from yesteryear were still in circulation, and still being actively used. While they were once the apple of our eye, we quickly jumped from them to the new breed of browsers. It wasn’t that Internet Explorer 3-8 were bad – they weren’t. It was the fact that the world around them changed, and changed quickly.

Fast forward to Internet Explorer 10; it is new, and has great support for standards. Most importantly though, it hints at having the capacity to auto-upgrade like its competition. So I was curious, do I have any reason to dislike Internet Explorer any longer? Is it just as good as Google Chrome, Mozilla Firefox, or Opera? What better way to find out than to use it as my primary Browser of Choice for one week.

Sunday, Bloody Sunday

It’s really tough retraining my mind to click my Internet Explorer icon instead of my Chrome icon. The icon that was once relegated to testing and debugging my code in yesterday’s browser is now my go-to destination for all casual browsing, tweeting, and more.

So far I’ve been using Internet Explorer for Bootstrap work, blogging from WordPress, Tweeting with TweetDeck, Facebook, and casual browsing online. While I didn’t spend much time in the browser today, I did do some tweeting from @tweetdeck’s web-application, and noticed that the scrollbars are pretty horrible looking – so I fixed them. Left and right for before and after.

ie-tweetdeck-css

Unfortunately it appears Twitter has neglected Internet Explorer when they developed their dark-theme. While they fixed up the styles for the scrollbar in WebKit, they failed to do anything remotely similar in Internet Explorer. I’ve notified them (and might have gotten their attention), so let’s hope they get word and make these changes. You can make similar changes in your applications using scrollbar-face-color and related properties (See the “see also” section on the previous link).

I must admit, it would be awesome if we could control the properties of the scrollbar by setting properties on a pseudo-element instead of on any element that scrolls. It’s worth noting that in this territory, there currently is no w3c-accepted standard.

IE uses a proprietary extension in the form of prefixed-properties, and WebKit uses a proprietary extension in the form of prefixed-pseudo-elements. One can only hope there will be a consensus and convergence in implementation.

No Case of the Mundays

Today was my first actual day of work in Internet Explorer. I mean, I’ve opened it up here and there during work in the past, but today I spent all of my time in Internet Explorer – and it went well. Nothing broke (that I noticed), nothing was complicated, all was well.

I did work on a CSS example for somebody today only to have them say “the antialiasing sucks,” but as it turned out they were viewing in Chrome, and I was viewing in Internet Explorer. Sure enough, if you create a hard-edge on an angled CSS gradient, it looks better in Internet Explorer than it does in Chrome. Here’s a quick comparison between Chrome 25 and Internet Explorer 10.

linear-gradient-aa

This particular gradient is 25deg – oddly enough, Chrome draws a beautifully-smooth line when the gradient is changed to 45deg rather than 25deg. Don’t ask me why – I haven’t the slightest clue.

OMG, Tuesday!

Wow, so today was a big day. When I started this blog post I was a little bummed that the only people able to take the IE Challenge would be those who have purchased Windows 8, or a machine that came loaded with Windows 8. This morning at 6am PST, the IEBlog announced Internet Explorer 10 for Windows 7!

On to my day though – today was spent largely in Google Docs. I noticed there were some small layout differences between Chrome and IE. For instance, the number of characters you can fit on one line before a wrap occurs differs in Chrome than it does in IE. This was particularly bothersome since one of my templates features right-aligned text left-padded with enough spaces to complete a full line of characters. All of these characters are then set with a dark background color.

I wound up taking an alternative route, replacing this approach with a single-cell single-row table, and setting the background color of the cell instead of the background color of the text. This was far better and gave far more consistent results between IE and Chrome. No clue who is to blame, or what was the means by which both browsers diverged from one another, but Chrome appeared to hold itself together better overall when it came to Google Docs.

Wednesday, Thursday, and Friday

So at this point it’s just difficult to find things to blog about. I instinctively click on the Internet Explorer 10 and go straight to my browsing. I don’t experience any issues with my favorite sites. I tweet using TweetDeck, check in with Mom on facebook, drop images into imgur, broadcast using Google Hangouts, manage a channel on YouTube, help out where possible on StackOverflow, and blog about all of it here in WordPress – no issues. Everything just works.

I don’t mean to give the impression that there isn’t any work to be done – there is, a lot. Sadly, while the Internet Explorer developers have been doing an amazing job with their product, we (the community) need to step up our game as well. We’ve got to start writing better code, and paying attention to language specifications and APIs, as well as the ways in which they’re implemented in various browsers.

I came across another “my site doesn’t work in IE” thread today. The website popped up in Quirks mode. Changing it to Standards didn’t magically fix it (as it does from time to time). Instead, pushing it to Standards mode resulted in an even more damaged experience.

The problem here was written all over the Source: apathy, carelessness, and so much more. We aren’t teaching passion for our craft today as well as we should. We teach people how to hammer out some markup, and then encourage them to feed off of the visual presentation, rather than the compliance to the specification (too). New developers code, and refresh, code, and refresh. Rarely, if ever, making a trip to w3.org.

In early 2012 I came across a rather iconic website that was rendering well in Chrome and Firefox, but the side-bar navigation (made up of lists within lists) was severely broken in Internet Explorer 9. The problem wound up being an unclosed list item; I modified the response in Fiddler, issued a new request in IE9, and the page magically worked. This designer tested their markup in a browser that deviated from what the code explicitly requested (nasty nesting), and instead did what it thought the designer intended. While this resulted in the proper formatting, it breaks the web.

This was something I grew to appreciate in Internet Explorer 9 – it was brutally honest. You got what you asked for (generally speaking), and when your document was looking ugly, it was because your code was telling it to. Other browsers would implement a dose of speculation into its rendering process, which adds far too much variability to the web.

Not Perfect, But Better

A week of using Internet Explorer as your primary browser convinces me of at least two things: 1) Microsoft has come a long way with their product, and it deserves a second look. And 2) There’s still work to be done. While surfing the web on Internet Explorer 10 doesn’t feel like sucking on broken glass, it still leaves some areas for improvement.

I try to be a little less critical about massive software, given the enormous complexity to create, develop, and maintain it, but there are areas where Internet Explorer 10 can be improved. I come across these items from time to time, and try to create simplified reproducible examples when possible to share with others (and with whomever I have access to within Microsoft). One such issue is the :hover bug related to table-rows. You can see this online at http://jsfiddle.net/jonathansampson/FCzyf/show/ (Tested in Internet Explorer 10 on Windows 8 only).

Even with its flaws, Internet Explorer is still leading the way in other areas. It’s currently one of the only browsers to support pseudo-element animation, the Pointer model (though you can get ‘Pointium‘), and some CSS level 4 text properties.

My biggest concern lately is not with the browser itself, Microsoft has convinced me that their product is reliable. What concerns me lately is with the release cycles. Can they keep this new browser breathing, or are they going to continue resuscitating it on a bi-annual cycle? If so, we’ll quickly find the web moving out ahead of it again, and history will repeat itself. I find a glimmer of hope in the newest “About Internet Explorer” dialog.

Install New Versions Automatically

In my sincere opinion, Internet Explorer (in just a few years) went from being the bane of my existence (#somuchdrama), to being a bright luminary, back competing in the pack of modern browsers. Will it stay among the pack? Time will tell. Until then, welcome back Internet Explorer.

Download Internet Explorer 10, give it a week, and post your results below.

Repeating Lateral Text Shadows

I’ve wanted to do this effect for some time now. It consists of one or more lines of text with variable indentation, and seemingly ever-repeating washed out copies of the text on both sides running off screen.

Decided to use text-shadow to implement it, though support is not as broad as I’d like to see. The primary pain in this is with the offset for the text-shadows. Due to the varying length of each line, you have to provide specific offsets for each line having the effect. This could a lot less painful if it were to be built with a preprocessor.

I’ve uploaded the demo over at Dabblet, JSFiddle, and CodePen. And for those who don’t have a browser that supports text-shadow, here’s a screenshot of the result:

shadows

One really neat side-effect of this approach is that because it uses shadows, it inherently gives off a responsive feel; in the demos above you can see that it extends as far left and right as its parent permits.

Update: Now Animated using @keyframes

CSS3 Marquees

I came across an old question on Stack Overflow that I answered years ago. It was asking how to scroll text, vertically, in a marquee-like fashion. At the time, I had answered that you would need to use Flash, or JavaScript/jQuery. I thought to myself, you would most certainly need to animate the top value of a positioned element, or maybe increase a negative margin or something.

Well, we live in a very different world today. And today, we have access to @keyframes, animation, and so much more in modern browsers. This got me wondering what type of simple marquee I could whip up in an instant (wound up playing with this for a little over an hour). What I came up with is posted below.

Take some time to read through the embedded comments, and play with the code. If you have any questions please feel free to post them in the comments below and I’ll assist as I am able.

Horizontal

Vertical

Sorting Arrays in JavaScript, from the Inside-Out.

Every now and then I come across questions on StackOverflow that require me to do a bit of thought-work. This particular question was asking to to take an array, such as [‘a’,’b’,’c’,’d’,’e’], and flip it inside out, so that it becomes [‘c’,’d’,’b’,’e’,’a’]. I’m not a particularly mathematical person, so when I discover a difficult to discern pattern, I get excited – such was the case with the code below.

// Arrays to sort
var data = ["a","b","c","d","e"],
    info = ["a","b","c","d"];

// Sort array from inside-out ['a','b','c','d','e'] 
// Resulting in the following ['c','d','b','e','a']
function gut (arr) {
    
    // Resulting array, Counting variable, Number of items, 
    // initial Location
    var out = [], cnt, 
        num = arr.length, 
        loc = Math.floor(num/2);
    
    // Cycle through as many times as the array is long
    for (cnt = 0; cnt < num; cnt++)
        // Protecting our cnt variable
        (function () {
            // If our array has an odd number of entries
            if (num % 2) {
                // If on an odd iteration
                if (cnt % 2) {
                    // Move location forward
                    loc = loc + (+cnt); 
                } else {
                    // Move location backwards
                    loc = loc + (-cnt);  
                }
            // Our array has an even number of entries
            } else {
                // If on an odd iteration
                if (cnt % 2) {
                    // Move location backwards
                    loc = loc + (-cnt);
                } else {
                    // Move location forwards
                    loc = loc + (+cnt);
                }
            }
            // Push val at location to new array
            out.push(arr[loc]);
        })()
            
    // Return new array
    return out;
    
}

// Test with two arrays; even and odd sizes.
console.log(gut(data), gut(info));​

Which results in the following output:

["c", "d", "b", "e", "a"]
["c", "b", "d", "a"]

Perhaps you will find some use for it.

Of Dice, Dabblet, and CSS

I discovered dabblet.com some time back and never really spent much time there. Don’t get me wrong, it made a great first impression, however I am not super-talented in the CSS department, and it seems to be a tool for those who are.

I decided to return this evening and try my hand at creating some dice with nothing but CSS. I recently became a Potentate of the Rose, so this was a relevant and timely interest. After a couple hours of distracted back-and-forth, I finally had something pretty attractive.

While I don’t consider myself much of a CSS power-house, dabblet.com made the tedious process of building these die super-fun and very palatable. If you find yourself giving dabblet a run (and I suggest you do it), be sure to thank @leaverou for all of her hard work on such an awesome tool.

The final result can be seen here, or in the framed demo below.

Crushing Code and Shaving Chars

Who has heard of Code Golf? I hadn’t up until about 3 years ago when I first stumbled across some on Stack Overflow. I faintly recall the horror as I gazed upon some of the most cryptic code ever – somewhat akin to the feeling I had the first time I was shown a regular expression.

According to Wikipedia, “Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible code that implements a certain algorithm.”

Now I would never claim to be able to hold my own against some of the veteran golfers, however I do find myself growing more and more interested in how I can shave off a few bytes here and there. Such was the case today when I set out to answer a question on Stack Overflow.

The OP was asking how he might take a single-dimension array of words, sort them alphabetically, and then print them out. Each new group of words, categorized by their first letter, should be preceded by that letter. So you would first see “A”, followed by all “a” words, then “B”, followed by all “b” words, and so on. I’ve personally wanted to do this in the past myself.

After a few minutes I had posted the following:

$firstChar = ''; 
sort( $aTest );

foreach ( $aTest as $word ) {
  $firstChar = substr( $word, 0, 1 );
  if ( $firstChar != $currChar ) {
    $currChar = $firstChar;
    echo $currChar;
  }
  echo $word; 
}

This is ugly, but fairly straight-forward. You cycle through the array, printing out the first letter of the current word whenever it differs from the last iteration. Simple enough. But then one of the members pointed out via comment that instead of writing

substr( $word, 0, 1 );

I could just access the first letter as though the word itself were an array:

sort( $aTest );

foreach ( $aTest as $word ) {
  if ( $word[0] != $currChar ) {
    $currChar = $word[0];
    echo $currChar;
  }
  echo $word; 
}

Now it had been a while since I did that. So I was pleased to be reminded of this. Then that little spark of brevity begin to grow, and I wanted to see where else I could shave off some chars. My eyes were then drawn to the assignment and echo portion:

$currChar = $word[0];
echo $currChar;

That would be shortened so that the assignment and echo take place all at once:

sort( $aTest );

foreach ( $aTest as $word ) {
  if ( $word[0] != $currChar ) {
    echo ( $currChar = $word[0] );
  }
  echo $word; 
}

So now it’s down to a single if statement, and a trailing echo. I wondered if I could just load this up into a ternary, so I set my hand to do that:

sort( $aTest );

foreach ( $aTest as $word ) {
  echo ( $word[0] != $currChar ) 
    ? ( $currChar = $word[0] ) . $word 
    : $word; 
}

At this point, I was getting a little OCD about my second and third expression. They seemed unbalanced. The second one was setting the new current category letter, as well as echoing out the word. The third one was just echoing out the word. This is when my mind returned to something Brendan Eich called an “abusage” – using && in somewhat of an if-statement fashion.

$cond && ($foo = 'bar');

The second part is only evaluated when the first part is determined to be true. If the first part is false, the operation short-circuits and the second part is never touched. I realized I could use this to test the equality of the current category letter and the first char of the current word. If they were not equal, I could use the right hand side of the operator to record the new letter:

sort( $aTest );

foreach ( $aTest as $word ) {
  echo ( $word[0] != $currChar ) && ( $currChar = $word[0] ) 
    ? $currChar . $word 
    : $word; 
}

Awesome. Looking very slim. Now that I have only one statement within my foreach loop, I can strip away the curly braces. I can also reduce even more space by moving away from long variables names. Instead of “word”, I can simply use “w”. Instead of “currChar”, I can use “l” (for “letter”). I can also collapse my ternary operator onto one line:

sort( $aTest );

foreach ( $aTest as $w ) echo ( $w[0] != $l ) && ( $l = $w[0] ) ? $l . $w : $w ;

Nearly there. Last we can strip out all of the white space possible. Unfortunately with the syntax of the foreach, we cannot remove the spaces around the keyword “as” in the condition.

sort($aTest);foreach($aTest as $w)echo($w[0]!=$l)&&($l=$w[0])?$l.$w:$w;

In the end we’ve reduced about 195 characters and 11 lines down to 1 line and roughly 70 characters! Granted, that’s nothing compared to what others have acheived, however it’s awesome to see this solution iteratively collapse before my very eyes.

With some clever substring alternatives, ternary operators, and hacking the way logical operators work, we’re able to reduce a dandy solution into a horrific and cryptic trace of insanity. I don’t suggest you actually produce code like this when you ship (outside of the obvious minification), as it’s far better to write readable code than it is to write short code.

In the end, I was able to switch away from the original array declaration and use the deprecated split function to save even more bytes:

$a=split(",","apple,pear,banana,kiwi,pineapple,strawberry");
sort($a);foreach($a as $w)echo($w[0]!=$l)&&($l=$w[0])?$l.$w:$w;

So how about you? Do you engage in this type of behavior? Have any tricks of the trade to share? Place them in the comments below! Or perhaps you can shorten my code even further – I’d love to see what you come up with!