04
Sat, May
5 New Articles

PHP: Variables, Arrays, and Functions (Don't Say It)

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

You've used arrays in RPG, but they're so much more important in PHP.

 

Last May, we talked about variables and how they're used in PHP. If you were paying any attention, which I wasn't, you know that PHP supports the following variable types: string (alphanumeric), integer, floating point (decimals), Boolean (true or false), array, object, null, and resource. Now we want to zero in on one of those variable types that we talked aboutnamely, arraysand look at how they're used.

You know what would be easy? To just read through this article and think, "Aw, that ain't so bad." But you would learn absolutely nothing that way. I want to encourage you to get WAMP or MAMP (or some sort of Web server) going on your machine, grab a text editor, and use the code samples in here to get some actual practice. Just remember that every script should start with <?php and end with ?>. And be sure to save your text files as .php.

Arrays

RPG has arrays, but the functionality in PHP for the array variable type is more robust than what RPG has, and you will have difficulty finding many PHP scripts that do not have a number of arrays in them. In general, there are two types of arrays in the PHP world: numeric and associative.

Numeric Arrays

The good news is that with one big yet small difference, numeric arrays in PHP are very similar to the kinds of arrays we RPG people are used to.

The word numeric refers not to the data kept in the array (that can be numeric or string) but rather to the subscript or index that's used to identify and access individual entries in the array. In a numeric array, they're…duh…numeric.

The primary difference between an RPG and a PHP array is that while in RPG the subscript starts with 1 (that is, the first element in an RPG array is indexed as 1), the first element in a PHP array is the 0 element. I know; it's crazy. But that's the way C does things, and when you get right down to it, PHP is written in C, so what can you do? If your parents are nuts, chances are you're going to be nuts too.

Creating an array is simple; just indicate the name and call it an array. There's no need to define the size of the array, the number of elements in it, or anything else when you create it; PHP will dynamically add space as needed.

$MyArray = array()

Look familiar? It should. Remember, an array is just a variable, so creating an array looks just like creating a variable except that, rather than defining it by moving a value to it, we define it by just declaring it to be an array.

The easiest way to put values in this array is to let PHP do the indexing for you. That is, PHP is able to see what the last index value used was and assign the next value to the next index value. To do this, simply use brackets instead of parentheses and don't enter an index value. For example:

$MyArray[] = 'Dave';

$MyArray[] = 'David';

$MyArray[] = 'Davey';

This will result (if this is the first time you're putting a value in this array) in the zero index spot being assigned the value 'Dave', the 1 index holds 'David', and lucky index 2 has 'Davey'.

You'll also use brackets if you're picking up a value from the array. The following example sets the variable $value to be equal to the 11th entry in the array.

 

$value = $MyArray[10]  

All in all, numeric arrays are pretty straightforward.

Associative Arrays

But PHP doesn't stop there. The second type of array that you can define is the associative array. Here, the index or subscript isn't a number, but rather a string. What's the point of that? Well, since you're defining the string value (rather than letting it default to the set of all integers starting with zero), you can assign values that actually have meaningthings like 'first name', 'last name', 'street address', etc.

That is, we could define an array that represents an address, with elements or indexes that represent the different parts of the address. And by defining it as an array, we can then move it as a unit rather than having to necessarily deal with the individual data elements.

$MyArray = array(

      'name'     => 'John Smith',

      'address' => '1304 Sherwood Ave',

             'city'         => 'Your City',

             'state'       => 'XX',

             'zip code' => '99999-9999'

);

In the above code, you have two "things"; for example, the 'name' and 'John Smith' connected by a => thingy. The 'name' is the property; this is the entity you're defining. The 'John Smith' is the value of the property. We'll see this below when we do a "foreach" to display the contents of the array. Also notice that there's only one semicolon (at the end of the whole thing), but there's a comma after every property/value pair except the last one.

One of the things that can be really confusing about PHP is the many number of ways that the same action can be coded. This is partly because PHP is free-form and partly because it's a Web language, and that means anything goes. So the array can also be set up horizontally. There's no real difference in the syntax; it just really depends on how you want to see things, what looks more intuitive.

$MyArray = array('name'=>'John Smith', 'address'=>'1304 Sherwood Ave',

         'city'=>'Your City', 'state'=>'XX', 'zip code'=>'99999-9999');

Or

$MyArray = array();

$MyArray['name'] = 'John Smith';

$MyArray['address'] = '1304 Sherwood Ave';

etc.

What's important to notice is that, in the first two formats, you use => to associate a property with a value. But in the third format, you use =. That's not a misprint; that's the way it is. I know. Confusing. But remember that when we set the numeric array earlier and we assigned values using the empty brackets, we also used an = sign there, so it does sort of make sense. Also, the first two have a semicolon only after the whole mess, but the last one, which is breaking it up into separate PHP statements, has a semicolon after each line.

Two-Dimensional Associative Arrays

The associative array above is neat, but it's really just a one-dimensional array. This is great if you have just one address or if all of the properties are the same type (like the names of cities or cars), but what if you have a more complex situation? You could use several arrays, of course, and that might make sense, but in the end we want to be able to create a multi-dimensional array where we can load multiple records.

Fortunately, defining two or three (or whatever) dimensional arrays in PHP is easy if not tedious. Using one of our formats from above, we expand it slightly.

$MyArray = array(array('name'=>'Dave', 'dob'=>'1985-05-15'),

                                   array('name'=>'David', 'dob'=>'1983-04-21'),

                                   array('name'=>'Davey', 'dob'=>'1981-02-06')

                                   );

We have now loaded a two-dimensional array that, in structure, looks strangely like a set of file records from RPG. Any time you're bringing data in from a subfile-like PHP scripted page (even though PHP never uses the term "subfiles") or reading records from a database (DB2, MySQL, etc.), you'll run into this type of construct. The same is true, of course, if you're writing data out to a file or page.

Following this basic format, you can create three or even more dimensional arrays, but the question then is, what would they represent?

Summary

Of greater interest is what we do now that we have data in an array, be it one- or 20-dimensional. While PHP supports a number of variable formats, arrays are one of the most useful for people who are doing business applications. And when you're developing application programs, you'll use arrays to hold both page data (data that's going to be displayed) and database information. This might have come from an RPG data structure, passed in on the call, where we're moving data out to a page or file, or else destined for an RPG data structure to be massaged and used by the program.

Either way, one of the most important activities after learning how to load data in a number of different types of arrays (numeric, associative one-dimension, associative multi-dimension) is how to pull that data out and display or post it. And that will be the topic of our next column. See ya!

David Shirey

David Shirey is president of Shirey Consulting Services, providing technical and business consulting services for the IBM i world. Among the services provided are IBM i technical support, including application design and programming services, ERP installation and support, and EDI setup and maintenance. With experience in a wide range of industries (food and beverage to electronics to hard manufacturing to drugs--the legal kind--to medical devices to fulfillment houses) and a wide range of business sizes served (from very large, like Fresh Express, to much smaller, like Labconco), SCS has the knowledge and experience to assist with your technical or business issues. You may contact Dave by email at This email address is being protected from spambots. You need JavaScript enabled to view it. or by phone at (616) 304-2466.


MC Press books written by David Shirey available now on the MC Press Bookstore.

21st Century RPG: /Free, ILE, and MVC 21st Century RPG: /Free, ILE, and MVC
Boost your productivity, modernize your applications, and upgrade your skills with these powerful coding methods.
List Price $69.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: