Removing Keys from an Array in PHP

Removing one or more keys from an array in PHP seems like something that should be easy to do. Yet out of the 70+ array functions in PHP, there is no single function to do it. But here’s the easy way:

Use array_diff_key()

PHP has a function called array_diff_key($array1, $array2) that returns an array with all of the keys (and their values) from $array1 that don’t also occur in $array2. We can use this to quickly cobble together a solution:

<?php
 
function array_remove_keys($array, $keys) {
 
    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }
 
    return array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, array('address2'));
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/

Works great! But it’s not quite complete. There is absolutely no error checking, and passing an array as the second parameter isn’t the most convenient way to operate. Let’s give the caller the option of passing either an array, or a comma-separated list of keys to delete.

<?php
 
function array_remove_keys($array, $keys = array()) {
 
	// If array is empty or not an array at all, don't bother
	// doing anything else.
	if(empty($array) || (! is_array($array))) {
		return $array;
	}
 
	// If $keys is a comma-separated list, convert to an array.
	if(is_string($keys)) {
		$keys = explode(',', $keys);
	}
 
	// At this point if $keys is not an array, we can't do anything with it.
	if(! is_array($keys)) {
		return $array;
	}
 
    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }
 
    return array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, 'address2');
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/

What is HTML?

Most people have heard the term HTML and have a general idea that it has something to do with the web.  But as someone who wants to create the web you need to have a better understanding.  This article will explain what HTML is and why it’s important, and it just might do it without boring you into a coma.

What is HTML?

Defining HTML is by far the most boring part of understanding it, so lets keep this brief. HTML is the format in which documents on the web are written. HTML stands for HyperText Markup Language. Let’s break that down into something digestible:

  • HyperText – Text with interactive references to other text or content (or, Words on Ritalin). These so-called references are what you probably know as hyperlinks.  Hyperlinks are what allows the web to be a web in the first place: they link documents together. Without Hyperlinks the documents, videos, and images that make up the web would be likes islands with no trade routes between them. In other words, Hyperlinks are what allows us to surf the web, and are responsible for countless hours of lost productivity (well, hyperlinks and FarmVille).
  • Markup Language – HTML is technically a computer language, but don’t let that scare you: it’s really easy! HTML is a very specialized language called a Markup Language which is used for describing, annotating, and structuring text. HTML exists for the same reason we space and indent paragraphs, quotes, and other sections of a written document: it provides context to the content, and breaks up long sections of text into manageable chunks. HTML also allows us to insert interactive content into our documents like images and videos.  So while writing HTML may sound as fun as diagramming a sentence, the payoff for understanding it is way cooler.

But keep this in mind: with the exception of people like us who create the web, humans don’t read HTML; web browsers do! HTML is designed to help browsers (like Firefox, Chrome, Safari, or Internet Explorer) understand our content.

HTML is a Standard (That Everyone Interprets Differently)

HTML was created by a physicist names Tim Berners-Lee, but today is managed by a group called the World Wide Web Consortium, or W3. The W3 is a group of member organizations (still led by Berners-Lee) charged with creating and improving web standards.  The W3 publishes the HTML standards and leaves it up to the web browsers to interpret them.  The important thing to remember about HTML standards are:

  • HTML is still changing.  The language has gone through a number of versions over the years, the latest (and as of yet non-standard) version being HTML 5.
  • Not all web browsers interpret and display HTML the same way. This is one of the most difficult hurdles to pass in publishing on the Internet, and removing that room for interpretation is one of the reasons that HTML standards change.

As someone interested in creating HTML content and publishing it on the web, it’s important that you keep your finger on the pulse of the W3 and the web in general.  HTML and web browsers change rapidly, and you’ll have to learn to change with it.

Summary

HTML is a specialized computer language for describing and structuring text.  It’s a form of hypertext, which is a specialized type of document that provides references to other documents and content called hyperlinks.  HTML is a standard controlled by the World Wide Web Consortium, but it’s up to browser manufacturers to interpret that standard, so the way your HTML documents are rendered can differ from browser-to-browser.

Was that so difficult?  Let’s move on to something a little more interesting.

For More Information

[amazon_link id=”006251587X” target=”_blank” ]Weaving the Web: The Original Design and Ultimate Destiny of the World Wide Web[/amazon_link] [amazon_link id=”0596527322″ target=”_blank” ]HTML & XHTML: The Definitive Guide (6th Edition)[/amazon_link]

A Reponse to “Web Programming is Hard!”

This article is a response to a blog post titled “Web Programming is Hard!” The author expresses her frustration at being denied interviews for web programming jobs because she comes from a desktop/embedded system development background.

Let me tell you a little story that may make you feel better about the difficulties of web programming.  I work at a school, and about a decade back (before I was hired) they commissioned a programmer to build a customized student information system.  You couldn’t meet a nicer guy, but he was an engineer who followed the money into Visual Basic development.  He’s a smart guy, but originally not a programmer by trade or training.

About four years back they reached the limitations of that program.  More people were using it over wireless, which caused the Access database on which the VB front-end relied to become corrupted.  It began getting slower.  His programming relied on a separate program that ran continuously on a server to calculate grades.  On top of that, some of the VB 6 controls have nasty rendering issues on Vista and Windows 7.  It was time for a rewrite.

The requirements set forth for this new application were, 1. It must be web-based, 2. It must use a full-fledged RDBMS (SQL Server was chosen), 3. It must have a parent module they can access from home. The programmer, having never developed a web application in his life, decided on a set of technologies he’d never used: C#, ASP.Net, Silverlight, and IIS.

It’s four years later and we don’t have a web application.  The desktop application we do have is alpha at best, still doesn’t have all the features of the original, doesn’t have a parent module, and requires me to install about 5 libraries (requiring 2 reboots) before I can install it.  The only requirement that was met was to use SQL Server, and we’re a little leary of that because he couldn’t make his program work without admin rights to our entire SQL Server. The only reason the project continues is because certain stakeholders feel too invested to throw in the towel.

This is the story of a perfectly intelligent man who bit off more than he could chew and failed to understand one simple idea: web applications run in a browser.  Web development is different.  As others have said, it’s not any more or less difficult than desktop development, but there is an entirely new set tools, requirements and obstacles that you need to understand going into it.

Even if you consider yourself an expert in other forms of programming my recommendation isstill  to start with HTML.  HTML is just markup and no logic (just like XML, it applies structure and meaning to data), so it’s generally easy to pick up.

Then learn CSS.  You don’t have to become an amazing designer, but understand positioning, the box model, and font sizing, before you move on.

Next learn JavaScript, and make sure to add jQuery or another framework to your toolbelt! It wasn’t so long ago that you could develop a successful web application with little to no JavaScript, but that’s not the case anymore.  JavaScript is an integral building block of the present and future web. Make sure you have a good understanding of JavaScript’s types (everything is an object), JavaScript scoping issues, closures, JSON (JavaScript Object Notation), and Ajax.

Once you have a good grasp of the client side, then pick a server-side tool, whether it be ASP.Net, PHP, Ruby or Java. Then start small.  Even if you already know the language from a desktop development standpoint, write a program that outputs a “hello world” HTML page first.  You can write the next Facebook tomorrow!