31
Thu, Nov
2 New Articles

PHP: Variables, Arrays, and Functions, Part 2

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

Love the idea of putting data in two-dimensional arrays? Well, the next step is figuring out how to get it out. But before you do that, there's one little thing.

 

In our last visit, we talked about arrays. We talked about the difference between numeric and associative arrays. We talked about how to load and unload data from them. And we talked about how to load data into two-dimensional associative arrays, which more or less mimic file records. Let's face it, we just couldn't shut up about them. But we delayed the discussion of pulling data out of those two-dimensional associative arrays until later. You might, of course, think that "later" is now, but unfortunately, before we do that, there's one other little thing that we should cover.

HTML and PHP

I've talked a lot so far about using PHP, and I've said more than once that PHP code can be embedded in HTML. But I haven't really talked about how that works.

First, let's ask ourselves, when do we use PHP? We use PHP whenever we need to do something that we can't do in straight HTML, like access file data. And, since HTML doesn't really have array support, this includes holding and manipulating data that we either get from a file or plan to write out to a file. (There are other times that we use PHP, but that's the use we're looking at now.) What this means is that we'll do a PHP statement and then display the results, using HTML, on the screen.

The question is, how do we combine PHP and HTML so that we can execute a command in PHP and then display it using HTML?

The first thing we have to do is tell the browser that we're about to do some PHP commands (remember, neither PHP nor HTML is compiled; it is instead interpreted by the browser engine). We do this by enclosing anything that uses PHP with the <?php and ?> tags. Then, within those tags, we can mix PHP (echo or print, for example) and HTML (h2 or ul, for another example) tags.

<?php

      echo "<h1>This is the table header</h1>";

<?

This is a trivial example, of course, but it gives you the idea. Note the beginning and ending PHP tags and then the fact that we use echo to display things on the screen. Note also that the HTML statement is in quotes (things in an echo are) and that there's a semicolon at the end, which is normal for a PHP statement. Pretty straightforward, but make sure you get the syntax.

Echo vs. Print

There are two ways to take data that you've played with in PHP and throw it onto a Web page: echo and print. In this article, I'm pretty much going to use echo, but print is just as valid. Are they the same? No, not quite, and here are the differences that may cause you to use one over the other at times.

First and least important, there is a speed difference. Echo is faster than print (because the print has a return value associated with it), and to some people that's important. In one spot, I thought I saw a 30% difference; in another, it was called "irrelevant." With the speed of today's processors, I don't worry too much about the speed of an individual instruction, but for some people it's very important. You make the call.

Second, print is sort of like a function, whereas echo is just an operator. That means that print can be used in more complex functions and can return a value to a variable. For example, let's consider the use of print in a statement like this:

$var1 = print "ABC";

The value of $var1 would be 1 after completion of this task. Consequently, you could use this variable (and the print operator) in more complicated statements. Because it can be used in such statements, print has a spot in the precedence table, although it's low on the table hierarchy. Bottom line, if you need to evaluate the results of your display statement, use print.

Third, you can attach multiple parameters to an echo, but only one to a print. This means that a single echo statement can print out multiple things (fields, lines, etc.). You have to be careful how you set it up; the parms are separated by commas, no parentheses.

            echo "First line", "<br>", "Second line";

This renders as such:

First line

Second line

At the same time, while print will allow only one parm, print will allow concatenation of multiple values (as will echo).

 

$name = "Dave";

      print "My Name is " . $name . ".";

This renders like so:

My Name is Dave.

For more information on echo and print, see the PHP Manual or Google PHP echo vs. print.

Skipping Lines

One of the annoying but probably quite logical things about HTML is that just starting a new line of text in the text editor does not mean you're starting a new line on the browser. To do that, you need to use an HTML break tag (<br>) as shown below.

            echo "First Line" . "<br>" . "Second Line";

This renders like so:

 

           First Line

     Second Line

Combining PHP and HTML Tags

Using just HTML, you can't specify a variable value in a text paragraph. But using PHP you can do that. Suppose we wanted to build a sentence kind of thing that included data and text.

One of the most important constructs is using the period or the comma (which we talked about above) to allow PHP and HTML elements to be used on the same line. In this case, the HTML elements are enclosed in quotes, the PHP elements are not, and the period symbol (or comma for echo only) is used to separate them. You can have a space before or after the period/comma for readability or not. It's up to you.

For example, if we want to code up a line that combines both HTML text and a PHP variable, it could look like this:

 

      $variable1 = "Start";

      $variable2 = "End";

echo "First variable is " . $variable1 . " and the second is " . $variable2 . ".";

This would render like this:

First variable is Start and the second is End.

Or perhaps you want to put some formatting into it:

 

           echo "<h3>" . "My first name is " . "<em>" . $variable1 . "</em>" . "?" . "</h3>";

This would render this way:

 

            My first name is Dave?

I know, looks kind of confusing to begin with, but it's really pretty simple once you play with it for awhile. Take it apart element by element and see what's in there.

Summary

What's important here is that generally it doesn't matter whether you use echo or print, although if you want to evaluate the result of your display, then you have to use print. And it doesn't matter if you separate things with commas or periods, although if you're using print, you can't use commas to separate.

What does matter is that with a little practice you'll be able to print out mixed variables and text with either operator and even be able to apply formatting to what you put out there, something that is indispensible if you want to have nice-looking data moved from your arrays to a Web page. And that brings us back to where we started: How do you pick up the data in a two- (or more) dimensional array and display it on the page? But for the details on that, you'll have to wait for the next installment.

 

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

$

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: