Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


Java/Open Source Daily

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Manipulating Data With PHP Arrays

Bookmark and Share

by Jason Gilmore

December 01, 2009

PHP's impressive array manipulation capabilities make it possible for you to perform high-flying acrobatics with your data. In this tutorial you'll learn how to use these capabilities to create the basic features of an online card game.

Introduction

The array is regularly mentioned alongside PHP's other supported data types, integers, strings, and floating points, to name a few. However, you'll in all likelihood spend more time creating, accessing, and manipulating arrays than any other data type, placing the array in rarified air in terms of its significance within the PHP language. In fact, PHP natively supports almost 80 functions created expressly for the purpose of navigating, sorting, reversing, and slicing arrays, among other tasks. In this tutorial we'll look at how you can use PHP arrays and several of the native functions to manipulate data in useful and exciting ways.

Creating an Array

Suppose you have an idea for a Web-based card game, and therefore need a convenient solution for manipulating a deck of virtual playing cards. Because an array seems the most logical approach, you can define one which will subsequently hold the card values like this:

$cards = array();

Following the definition, you're free to begin adding values. Each of the following two approaches accomplishes the same task of adding the queen of spades to the deck:

$cards[] = "QS";
array_push($cards, "QS");

However, rather than add the cards one at a time, you could just add all of them like this:

$cards = array("JC", "JD", "JH", "JS",
               "QC", "QD", "QH", "QS", 
               "KC", "KD", "KH", "KS", 
               "AC", "AD", "AH", "AS"); 

To ensure the user understands exactly which cards are in his possession, you might consider using a multi- dimensional array which contains both the abbreviation and a user-friendly name for each card:

$cards = array("JC" => "Jack of Clubs",
               "JD" => "Jack of Diamonds",
               "JH" => "Jack of Hearts",
               "JS" => "Jack of Spades",
               "QC" => "Queen of Clubs",
               "QD" => "Queen of Diamonds",
               ...
               );

In order to keep things nice and tidy, for the remainder of this tutorial I'll use an array consisting of just four values:

$cards = array("JC" => "Jack of Clubs",
               "QD" => "Queen of Diamonds",
               "KH" => "King of Hearts",
               "AS" => "Ace of Spades");

Shuffling the Deck

With the deck created, we'll probably want to shuffle the cards in an attempt to ensure an even distribution. If the array were indexed you could use the shuffle() function, however we need a slightly more complicated approach in order to shuffle our associative array:

function shuffleAssociative($array)
{
  while(count($array) > 0)
  {
    $value = array_rand($array);
    $shuffled[$value] = $array[$value];
    unset($array[$value]);
  }
  return $shuffled;
}

With shuffleAssociative() defined, just call it like so:

$shuffled = shuffleAssociative($array);

Outputting the shuffled array using print_r() produces the randomized ordering:

Array ( [AS] => Ace of Spades [JC] => Jack of Clubs [KH] => King of Hearts [QD] => Queen of Diamonds ) 

Cutting the Deck

To make sure no funny business has occurred when the deck was shuffled, a player will probably want to cut the deck. You can simulate this action using the array_splice() and array_merge() functions. The array_splice() function will remove a portion of the array, the portion size defined by an indexed starting point and length. For instance, the following call will remove the first two elements of the shuffled deck:

$cut = array_splice($shuffled, 0, 2);

Next, we'll need to place the remaining portion of the shuffled deck on top of the cut portion. This is done using the array_merge() function, which will merge two arrays together:

$shuffled = array_merge($shuffled, $cut);

Dealing the Cards

With the deck shuffled it's time to deal the cards! Exactly how this is done will depend upon the number of players, and the number of cards which are supposed to be dealt to each player, so start by defining both of these constants:

define("NUM_PLAYERS", 3);
define("CARDS_PER_PLAYER", 4); 

Next we'll again use the array_splice() function to deal the cards:

$hands = array();

$x = 0;

while ($x < NUM_PLAYERS) {
  $hands[] = array_splice($shuffled, 0, CARDS_PER_PLAYER);
  $x++;
}

Displaying the Hands

We can display each player's hand using two more native functions, namely join() and array_keys(). The join() function will join an array elements together in a string, with each element separated by a predefined delimiter. The array_keys() function will return all of the keys in an array. Using these two functions together, we can loop through the $hands array, displaying each hand:

while($x < count($hands))
{
  echo "<p>PLAYER HAND: ". join(", ", array_keys($hands[$x]))."</p>";
  $x++;
}

Assuming three players each receiving four cards per hand, sample output (using a deck containing all of the face cards in addition to the aces) will look like this:

PLAYER HAND: JS, JC, KC, QD
PLAYER HAND: AC, QH, QC, JD
PLAYER HAND: KD, AH, JH, KH

Choosing a Discard

If we're playing a simple game in which each user will discard a card in his hand in the hopes of having the card of the highest value (Jacks being the lowest value cards, Aces being the highest), each user can choose a card simply by referring to the array key. For instance, this is how Player 1 would choose the Jack of Spades:

$discard = $hands[0]['JS'];

The $discard variable will now hold the value Jack of Spades.

Where to From Here?

Using PHP's impressive set of array manipulation functions, the sky is really the limit in terms of the types of card games you could create. If you happen to build upon what you've learned in this tutorial, I'd love to hear about it! Contact me via EasyPHPWebsites.com with your ideas.

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Formerly Apress' open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry’s most respected publishing programs. Over the years he's authored several other books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer’s conference, and was a member of the 2008 MySQL Conference speaker selection board.

Jason has published more than 100 tutorials and articles within prominent publications such as Developer.com, Linux Magazine, and TechTarget.



Up to => Home / Authoring / Tutorials / PHP