Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-BCA-SEM-V-Web Development using Php-Web Technologies-Second Draft

CU-BCA-SEM-V-Web Development using Php-Web Technologies-Second Draft

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-02-26 02:13:13

Description: CU-BCA-SEM-V-Web Development using Php-Web Technologies-Second Draft

Search

Read the Text Version

BACHELOR OF COMPUTER APPLICATIONS SEMESTER-V WEB DEVELOPMENT USING PHP / WEB TECHNOLOGIES First Published in 2021 All rights reserved. No Part of this book may be reproduced or transmitted, in any form or by any means, without permission in writing from Chandigarh University. Any person who does

any unauthorized act in relation to this book may be liable to criminal prosecution and civil claims for damages. This book is meant for educational and learning purpose. The authors of the book has/have taken all reasonable care to ensure that the contents of the book do not violate any existing copyright or other intellectual property rights of any person in any manner whatsoever. In the event, Authors has/ have been unable to track any source and if any copyright has been inadvertently infringed, please notify the publisher in writing for corrective action. CONTENT Unit - 1: Introduction To Php ................................................................................................ 4 Unit - 2: Introduction To Language Constructs.................................................................... 21 Unit - 3: Arrays ................................................................................................................... 43 Unit - 4: Function................................................................................................................ 65 Unit - 5: Php Forms............................................................................................................. 90 Unit - 6: Regular Expressions............................................................................................ 101 Unit - 7: Objects................................................................................................................ 109 Unit - 8: Php File Handling ............................................................................................... 115 2 CU IDOL SELF LEARNING MATERIAL (SLM)

Unit - 9: Php Session & Cookies ....................................................................................... 143 Unit - 10: Php Mysql......................................................................................................... 151 Unit - 11: Fetching Functions ............................................................................................ 176 Unit - 12: Ajax .................................................................................................................. 192 Unit - 13: Php Framework................................................................................................. 201 Unit - 14: Wordpress......................................................................................................... 212 Unit - 15: Pages And Posts................................................................................................ 234 3 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 1: INTRODUCTION TO PHP STRUCTURE 1.0 Learning Objectives 1.1 Introduction 1.2 PHP for Web Development & Web Applications 1.3 History & Future Scope of PHP 1.4 Installation of tools for working in PHP like XAMPP, LAMP, WAMP for PHP Apache & MySQL 1.5 Summary 1.6 Keywords 1.7 Learning Activity 1.8 Unit End Questions 1.9 References 1.0LEARNING OBJECTIVES After studying this unit, you will be able to:  Use of PHP for Web Development & Web Applications  Future Scope of PHP.  Learn the step of Installation of tools for working in PHP  Learn the installation of XAMPP, LAMP, WAMP for PHP Apache & MySQL 1.1 INTRODUCTION The personal home page is an open-source, translated, and object-orientated scripting dialect that may be accomplished at the server aspect. Hypertext Preprocessor is nicely appropriate for internet advancement. In this way, it's far utilized to create internet applications (a utility that executes on the server and produces the active page.). Personal home page turned into made by using Rasmus Lerdorf in 1994 but showed up inside the advertisement in 1995. Php 7. Four. Zero is the maximum recent shape of PHP, which become discharged on 28 November. Some critical focuses ought to be taken notice about PHP areas observed: Php stands for the personal home page. Hypertext Preprocessor is a deciphered dialect, 4 CU IDOL SELF LEARNING MATERIAL (SLM)

Hypertext Preprocessor is faster than different scripting dialects, for example, asp, and JSP. Hypertext Preprocessor might be a server-facet scripting dialect, that is applied to oversee the dynamic content of the internet site. The personal home page can be inserted into HTML. Hypertext Preprocessor is an object- oriented language. The personal home page is an open-supply scripting language. Php is simple and simple to memorize dialect. 1.2PHP FOR WEB DEVELOPMENT & WEB APPLICATIONS PHP for web Development Here are some of the reasons why PHP is used for web Development: • Easy to learn: Compared to other languages like Java and C, PHP is much easier to learn and easy to use too. • Open Source and Free: The components of the language are free to use since it is an open source. So, all you have to do is contact PHP Development Company and your job can be done easily and in a cost-effective manner. • Cross-Platform: PHP can run on all the major OS like Mac OSX, Windows, and Linux thus saving lots of time for developers. • Easy to Deploy: Deploying a PHP is easy and at a low cost since many hosting companies willing to offer a server for running the website. • Less Time to market: One of the factors that many custom software development companies prefer to use PHP for web development is because of its less time to market feature. This will allow any enterprise to gain better popularity than the competitor. • Reliable: Depending on how the developer codes, the web language can turn out to quite efficient. It is also scalable when the codes are written, thus making it a reliable language. • Faster Processing: PHP uses its own memory space; it automatically reduces the loading time and server workload. Thus, giving it better and faster processing capacity. Hence it is effective for websites that have high traffic. • Built-in function: Many useful tasks like sending emails, generating GIPFs, PDF documents and connecting to other network servers can be done with PHP since it has its own libraries. • Secured: This is one language that has one of the best layers of security protection in the market. Hence developing a website or app with PHP is much more secure than any other language. 5 CU IDOL SELF LEARNING MATERIAL (SLM)

• User-friendly: The simplicity of any website or app created with PHP makes it user- friendly since it is easy to understand and use. • Tested and Proven: Over millions of people have been using websites created with PHP for over two decades. It’s abilities and functions have been tested time and again and have proven to stand the test of time. • Extensions: The extensions in PHP allow modifying the source code file and managing them too making it the most used language by the developers. • Flexible: The functionalities of a website or an app might need changing several times when it is being developed or later too, PHP allows a seamless way to do that without any hassle. • Easy to Integrate: With PHP you do not have to re-code and re-develop as it can easily integrate with the current company software. • Supportive community: PHP has a large community of developers who keeps updating the forums with news and benefits. It is a reliable source of information on PHP and other related issues. So, if you ever get stuck the PHP community is there to support you PHP for web applications After the huge spread of the Internet and web pages, people started to look for ways to add dynamic functionality to their websites. These attempts went so far, that nowadays we're able to achieve the same behaviour on our web application as we would on our desktop apps. example, MS Word, and Office 365, or Google Docs web applications. The way web applications work is mainly through the client requesting specific documents from the server. Whereas on the server, there would be a CGI script running (a program that generates HTML files based on the user's request). The website would no longer be a simple file on the server, but a dynamically created version of itself each time a client request it (based on the actual request). PHP is the most popular language used for developing web applications 6 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 1.1 Working of web application The web-utility interaction situation frequently looks as if this: 1. The consumer enters a website address (URL) internal in his/her internet browser (as an instance eshop. Com/printer-epson-123) and with the aid of doing that, he/she sends a request to the server. 2. The server calls the Hypertext Pre-processor module. Three. The PHP module handles the request (in this case, the user desires to show records approximately a printer), connects to the database, and has hundreds of the corresponding records. Based totally on that, it generates an HTML document. 4. This HTML report is despatched to the customer - wherein he/she could most effectively be able to see a static website. Though, the website changed into truly dynamically created primarily based on his/her request. All the statistics are saved in a database, where the internet application (and its e-save in this example) has an administration interface through which personnel is effortlessly able to upload new products, edit costs, etc. If all of those facts weren't saved inside the database, every product would need to have its own static HTML record (which would make it extraordinarily difficult to control the pages). Additionally, without databases, there could be no manner to filter out merchandise by way of fee or write reviews approximately the goods, and so on. 7 CU IDOL SELF LEARNING MATERIAL (SLM)

Now that we have protected how dynamic websites paintings and additionally showed a brief instance, let's move over the professionals and cons of web applications  Easy administration - Once we upload a new version of the application, all of the users would instantly be switched to the new version.  High security - Both the website and the database are on the server. Unless they contain a security bug. Either way, it's really hard to steal a web application.  Huge user base - People are lazy and don't like downloading and installing applications. The cool thing is that all they have to do to use a web application is click on a link and they would be able to use it straight-away. If the same application was released as a desktop app, it wouldn't have as many users. Remember, applications are intended for users! No matter if they're free or paid, we always want as many people to use them as possible. This is the main reason why most applications that are on the web last for years.  High compatibility - Since we have access to the website through a web browser, we won't have to worry about the user's operating system and our application would work practically everywhere (even on smartphones).  We would also have the advantages of having client computers because the server isn't exhausted by displaying the website, the web browser does that for us. We will see that net programs are destiny, and being capable of creating them is a remarkable gain at the same time as searching out employment. The best downside nicely worth citing is that their improvement is a bit greater tough than the development of computing device applications. Mainly because of the fact the internet changed at the beginning designed for static files, so there are a few barriers that we are able to need to work around. But the internet era is ever-improving and lots of things are manner less difficult to do now than earlier than. Especially way to new internet requirements like HTML 5 and CSS 3. Greater complex internet programs usually pass hand in hand with one-of-a-kind programming languages like JavaScript, which runs at the patron's computer and handles the visible part of the application. JavaScript is used for dynamic net site extensions and its importance grows with complicated internet applications. 1.3 HISTORY & FUTURE SCOPE OF PHP History of PHP Hypertext Preprocessor is an \"HTML-embedded scripting language\" on the whole used for dynamic internet applications. The first part of this definition method is that Hypertext Preprocessor code can be interspersed with HTML, making it easy to generate dynamic portions of net pages. As a scripting language, personal home page code requires the presence 8 CU IDOL SELF LEARNING MATERIAL (SLM)

of the Hypertext Preprocessor processor. Php code is normally run in undeniable-textual content scripts as a way to most effective run-on PHP-enabled computers (conversely programming languages can create standalone binary executable documents). The personal home page takes most of its syntax from c, java, and Perl. It's miles an open-source era and runs on most running systems and with maximum internet servers. Hypertext Preprocessor was written within the c programming language by means of Rasmus Lerdorf in 1994 to be used in monitoring his online resume and related private record. For that reason, the personal home page at the start stood for \"personal home page\". Lerdorf blended Hypertext Preprocessor with his very own shape interpreter, liberating the combination publicly as Hypertext Preprocessor/fi (normally called personal home page 2. Zero) on June eight, 1995. Two programmers, Zeev Zurawski and Andi Gutman rebuilt Hypertext Preprocessor's middle, releasing the up-to-date result as Hypertext Preprocessor/fi 2 in 1997. The acronym has become formally changed to Hypertext Preprocessor: PHP, at the moment. (That is an example of a recursive acronym: in which the acronym itself is in its very own definition.) in 1998, PHP 3 turned launched, which turned into the first broadly used model. Php four changed into released in can also 2000, with a new core, called the Zend engine 1. Zero. Php four featured improved velocity and reliability over PHP 3. In phrases of capabilities, Hypertext Preprocessor four introduced references, the Boolean kind, com assist on windows, output buffering, many new array features, multiplied object-oriented programming, the inclusion of the PCRE library, and greater. NuSphere's PHP's MySQL wizardenlarge Php 5 was launched in July 2004, with the updated Zend engine 2.0. Most of the many new features in PHP 5 are: Stepped forward item-oriented programming Embedded SQLite Help for brand new MySQL capabilities (see the photo at right) Exception handling the use of an attempt, Catch shape Integrated cleaning soap guide (see the picture at proper) The filter library (in PHP 5.1) Better XML gear Iterators And plenty, a good deal extra. Nusphere's phped's soap wizardenlarge Php 6 has been in improvement due to the fact that October of 2006. The maximum enormous change might be native help for Unicode. Unpopular, deprecated capabilities which include magic quotes, register_globals, safe_mode, and the http_*_vars variables will 9 CU IDOL SELF LEARNING MATERIAL (SLM)

disappear in Hypertext Preprocessor 6. Even though personal home page remains on the whole used for server-side generation of web pages, it is able also to be used to carry out command-line scripting or to create graphical programs with the assist of gtk+. Destiny of personal home page Another purpose because PHP can be used for net improvement in 2021 is a wide-unfold implementation of progressive web apps and unmarried web page programs. Hypertext Preprocessor preferably suits for constructing the returned-give up for these styles of net programs. Unmarried web page programs (spas) represent a single-net web page format this is extremely speedy and responsive. It has an easy structure that excludes any complicated navigation or deep menus. Spas dynamically replace the information on an internet page without the need to reload it totally in a browser. As a result, such net applications paintings lots faster than fashionable internet programs, and their development employs less time. Progressive internet apps (pwas) is a neat development solution that mixes excellent internet and cell packages. Pwas use an internet browser and a set of APIs to run on any cellular platform. Its manner that pwas appear to be neighborhood mobile apps and are available on android and ios even as having internet components interior. Pwa applications assist them to gain extra capability clients whilst offering an exquisite client enjoy. 1.4INSTALLATION OF TOOLS FOR WORKING IN PHP LIKE XAMPP, LAMP, WAMP FOR PHP APACHE & MYSQL Downloading and installing PHP Web applications mostly use the Linux OS, Apache web-server, MySQL database and the PHP programming language. We usually abbreviate them as LAMP for short. They're all free of charge. If we run them on Windows, they may be referred to as WAMP. Probably the most popular installation package including Apache, PHP, and MySQL is called XAMPP. Its installation is very simple. Downloading XAMPP Go ahead and download the XAMPP package from the official website http://www.xampp.org/ To do so, find the XAMPP for Windows link. There you will see a Download title that you will have to click on to download the Installer as shown in the image below: 10 CU IDOL SELF LEARNING MATERIAL (SLM)

Installing It would be best if you run the installation as an administrator. To do that, right-click on the file and choose \"Run as administrator\". You'll probably see a message about UAC, just click OK. You may get a notification message saying that you are missing a Microsoft Visual C++ runtime, one that is required by XAMPP. If you happen to see a message like that, just confirm it. It'll open your web browser on the page where you can download the Microsoft Visual C++ runtime. Once you install it, you will be able to continue with the XAMPP installation. The XAMPP installation is easy and you mostly just have to click \"Next\". You'll be able to choose what parts of the package you wish to install. Despite us leaving the default configuration, we'll take this moment to explain each of the components do: Server Here we can choose exactly what we want on our server.  Apache - The web-server that allows for use to communicate with the client. We will absolutely need this one. 11 CU IDOL SELF LEARNING MATERIAL (SLM)

 MySQL - A popular database that includes the user-friendly phpMyAdmin database administration tool. There are several other databases, SQLite for example, that are included in PHP.  FileZilla FTP server - This one allows for us to create our own FTP server to which we can connect afterward. It requires a public IP address.  Mercury Mail Server - Local SMTP server for email correspondence.  Tomcat - A serverlet for Java that is useful for when you create websites in this programming language. Program languages You can also choose what programming languages you'd like to use on the server.  PHP - PHP is included by default.  Perl - You can also run Perl. Tools Other tools offered by the XAMPP package include:  phpMyAdmin - A user-friendly MySQL database administration tool.  Webalizer - A website-access statistic tool.  Fake Sendmail - Provides the sending of anonymous emails. If there is a service you don't want on the server, simply un-select it, but I highly recommend that you install everything just in case. You can choose which services to run on the server and which to turn off so you won't have to use them if not needed. 12 CU IDOL SELF LEARNING MATERIAL (SLM)

In the next window, keep the default C:\\xampp\\ folder, there could be problems with writing privileges to the Program files\\ folder otherwise. 13 CU IDOL SELF LEARNING MATERIAL (SLM)

During the installation, you might need to confirm to allow internet access to the services being installed. 14 CU IDOL SELF LEARNING MATERIAL (SLM)

When the installation finishes, you'll be asked if you'd like to start the XAMPP control panel. Go ahead and hit confirm. The control panel Once the application starts, we'll see the following form: Here, we are able to view all of the installed services. The most important parts are the Start/Stop buttons for the Apache and MySQL services. Using these, we can start or stop these services. It's always a good idea to stop them when we aren't using them, as they'd use up your performance otherwise. You can also check whether each service should run as a system service using the checkbox. READ CAREFULLY! If you're using Skype, you won't be able to start Apache! This is due to the fact that Skype isn't programmed properly and uses port 80 when it is not meant for it. You can fix that by changing Skype's port or by closing Skype - starting Apache - and starting Skype up again. We can run administration tools or view logs for a given service using the other buttons. If you got both services running, you're done with this part! IDE We now have the PHP environment ready for use. The only thing left to do is download an application that will allow us to write PHP code. We will not be using Windows Notepad. PHP is a dynamic language, so we would end up making plenty of mistakes there. We need something smart that will check our source code and auto-complete it. 15 CU IDOL SELF LEARNING MATERIAL (SLM)

I recommend using the PhpStorm IDE. It has high-quality tools and is used to develop the ICT.social information system. It comes with many functions that can save you a lot of time. The best free-to-use IDE is probably NetBeans. Although it isn't very \"smart\" and is kind of slow. You could download it at the following URL: http://www.netbeans.org, and choose the version for PHP development. Click through the installation and start-up NetBeans. We'll create a new project (File -> New project), choose PHP application, and name it HelloWorld. This name is used for when someone is making their very first application in a programming language. The sole purpose of HelloWorld applications is to print text. Which is exactly what we're going to program with the time we have left for today 16 CU IDOL SELF LEARNING MATERIAL (SLM)

The Project path should be the same as our PHP scripts folder. By default, it's C:\\xampp\\htdocs\\. Last, of all, we'll choose to use the local webserver (our Apache from XAMPP) and confirm. 17 CU IDOL SELF LEARNING MATERIAL (SLM)

1.5SUMMARY  Php has many benefits, and indexed right here are definitely a number of the reasons for the fulfillment of Hypertext Pre-processor. Many human beings will provide their very own reasons for the use of PHP - and this reality by myself is testimony to the electricity and flexibility of PHP.  Now that we recognize a bit about PHP and feature a top-level view of the manner it really works, we are able to start looking at how to increase Hypertext Pre-processor based totally definitely internet web sites, beginning with growing an easy personal home page script. 1.6 KEYWORD  XAMPP- XAMPP is an acronym, in which \"X\" stands for Multiplatform, \"A\" stands for Apache server, \"M\" stands for MariaDB, \"P\" stands for Perl, and \"P\" stands for PHP  WAMP- WAMP is another local server, which is a package of software including Apache Server (which stands for A), MySQL database (which stands for M), and PHP script-based language (which stands for P). The \"W\" in WAMP designates its exclusiveness for the Windows Operating system  MAMP- MAMP is a local server, which is compatible with (M) Mac Operating system and supports development & testing of web projects based on (A) Apache Server, (M) MySQL Database and (P) PHP OOPS based programming language.  LAMP- It is an acronym in which \"L\" stands for Linux, \"A\" stands for Apache, \"M\" stands for MySQL, and \"P\" stands for various programming languages such as PHP, Perl, and Python  HTML- HTML stands for hypertext markup language. It is a hypertext markup language used to create web pages. It is written in the form of HTML elements. 1.7 LEARNING ACTIVITY 1. Install XAMPP server and configure control panel. ___________________________________________________________________________ ___________________________________________________________________________ 2. Install Apache & MySQL. ___________________________________________________________________________ ___________________________________________________________________________ 18 CU IDOL SELF LEARNING MATERIAL (SLM)

1.8 UNIT END QUESTIONS 19 A. Descriptive Questions Short Questions 1. Is PHP a case sensitive language? 2. What is the meaning of ‘escaping to PHP’? 3. What is PHP? 4. What is the common usage of PHP? 5. In how many ways you can embed PHP code in an HTML page? Long Questions 1. What are the common uses of PHP? 2. How to install XAMPP server? 3. How to configure Server for PHP development? 4. Describe the advantage of PHP. 5. Explain the history and future of PHP? B. Multiple Choice Questions 1. What does PHP stand for? i) Personal Home Page ii) Hypertext Preprocessor iii) Pretext Hypertext Processor iv) Preprocessor Home Page a. Both i) and iii) b. Both ii) and iv) c. Only ii) d. Both i) and ii) 2. PHP files have a default file extension of_______ a. html b. xml c. php d. ph 3. What should be the correct syntax to write a PHP code? a. < php > CU IDOL SELF LEARNING MATERIAL (SLM)

b. < ? php ?> c. <? ?> d. <?php ?> 4. Which of the following is/are a PHP code editor? i) Notepad ii) Notepad++ iii) Adobe Dreamweaver iv) PDT a. Only iv) b. i), ii), iii) and iv) c. i), ii) and iii) d. Only iii) 5. Which version of PHP introduced Try/catch Exception? a. PHP 4 b. PHP 5 c. PHP 6 d. PHP 5 and later Answers 1-d, 2-c, 3-c. 4-b, 5-d 1.9 REFERENCES Textbooks  T1: Steven Holzner, WordPress-The Complete Reference, McGraw-Hill.  T2: Robin Nixon, WordPress-MySQL-JavaScript, O’Reilly. Reference Books  R1: Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, Ric McGredy, Wordpress, O’Reilly, Shroff Publishers. 20 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 2: INTRODUCTION TO LANGUAGE CONSTRUCTS STRUCTURE 2.0 Learning Objectives 2.1 Introduction 2.2 Variables 2.3 Constants 2.4 Data types 2.5 Loops 2.6 Comments 2.7 Outputting Data to the Browser 2.7.1 print () 2.7.2 echo () 2.7.3 print_r() 2.8 Summary 2.9 Keywords 2.10 Learning Activity 2.11 Unit End Questions 2.12 References 2.0LEARNING OBJECTIVES After studying this unit, you will be able to:  Declare and initialise Variables  Declare and use constants  Explain different data types  Implement different types of loops 2.1INTRODUCTION A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” 21 CU IDOL SELF LEARNING MATERIAL (SLM)

although the terms “constant” and “named constant” are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution, i.e., the value is variable. Like any other language, loop in PHP is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times. 2.2VARIABLES Naming and Creating a Variable in PHP Before learning how to declare a variable in PHP it is first important to understand some rules about variable names (also known as variable naming conventions). All PHP variable names must be pre-fixed with a $. It is this prefix which informs the PHP pre-processor that it is dealing with a variable. The first character of the name must be either a letter or an underscore (_). The remaining characters must comprise only of letters, numbers or underscores. All other characters are deemed to be invalid for use in a variable name. Let's look at some valid and invalid PHP variable names: $_myName // valid $myName // valid $__myvar // valid $myVar21 // valid $_1Big // invalid - underscore must be followed by a letter $1Big // invalid - must begin with a letter or underscore $_er-t // invalid contains non alphanumeric character (-) Variable names in PHP are case-sensitive. This means that PHP considers $_myVariable to be a completely different variable to one that is named ''$_myvariable. Assigning a Value to a PHP Variable Values are assigned to variables using the PHP assignment operator. The assignment operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assignment operator. Finally, the line, as with all PHP code statements, is terminated with a semi-colon (;). Let's begin by assigning the word \"Circle\" to a variable named myShape: $myShape = \"Circle\"; 22 CU IDOL SELF LEARNING MATERIAL (SLM)

We have now declared a variable with the name myShape and assigned a string value to it of \"Circe\". We can similarly declare a variable to contain an integer value: $numberOfShapes = 6; The above assignment creates a variable named numberOfShapes and assigns it a numeric value of 6. Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach: <?php $numberOfShapes = 6; // Set initial values $myShape = \"Circle\"; $numberOfShapes = 7; // Change the initial values to new values $myShape = \"Square\"; ?> Accessing PHP Variable Values Now that we have learned how to create a variable and assign an initial value to it, we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created. For example, if we want to display the value which we assigned to our numberOfShapes variable we can simply reference it in our echo command: <?php echo \"The number of shapes is $numberOfShapes.\"; ?> This will cause the following output to appear in the browser: The number of shapes is 6. Similarly, we can display the value of the myShape variable: <?php echo \"$myShape is the value of the current shape.\"; ?> 23 CU IDOL SELF LEARNING MATERIAL (SLM)

The examples we have used for accessing variable values are straightforward because we have always had a space character after the variable name. The question arises as to what should be done if we need to put other characters immediately after the variable name. For example: <?php echo \"The Circle is the $numberOfShapesth shape\"; ?> Unfortunately, PHP will see the th on the end of the $numberOfShapes variable name as being part of the name. It will then try to output the value of a variable called $numberOfShapesth, which does not exist. This results in nothing being displayed for this variable: The Circle is the shape. Fortunately, we can get around this issue by placing braces ({and}) around the variable name to distinguish the name from any other trailing characters: <?php echo \"The Circle is the ${numberOfShapes}th shape\"; ?> Changing the Type of a PHP Variable As we mentioned at the beginning of this chapter, PHP supports a number of different variable types (specifically integer, float, Boolean, array, object, resource and string).First, we are going to look at changing the type of a variable after it has been created. PHP is what is termed a loosely typed language. This contrasts with programming languages such as Java which are strongly typed languages. The rules of a strongly typed language dictate that once a variable has been declared as a particular type, its type cannot later be changed. In Java, for example, you cannot assign a floating-point number to a variable that was initially declared as being a string. Loosely typed languages such as PHP (and JavaScript), on the other hand, allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it: <?php $myNumber = 6; // variable is of integer type 24 CU IDOL SELF LEARNING MATERIAL (SLM)

$myNumber = \"six\"; // variable has now changed to string type ?> The process of dynamically changing the type of a variable is known as automatic type conversion. Checking Whether a Variable is Set When working with variables it is often necessary to ascertain whether a variable actually has a value associated with it or not at any particular point in a script. A mechanism is provided with PHP to provide this ability through the isset () function. To test whether a variable has a value set simply call the isset () function passing through the name of the variable as an. The following code example tests to see if a variable has a value or not and displays a message accordingly: <?php $myVariable = \"hello\"; if (isset($myVariable)) { echo \"It is set.\"; } else { echo \"It is not set.\"; } ?> If you 2.3CONSTANTS Constants are like a variable, except that their value never changes during execution once defined. 25 CU IDOL SELF LEARNING MATERIAL (SLM)

 The constant value is immutable.  Constant within a script is accessible to any area; however, they can be scalar values.  Constant names are case-sensitive, and they also follow the same naming requirements like variables, except the leading $.  It is considered best practice to define constants using only upper-case names. PHP define () function defines a constant. Syntax: bool define (string $name, mixed $value [, bool $case_insensitive = false]) Parameters Description name The name of the constant. value The values of the constant; only scalar and null values are allowed. Scalar values are an integer, float, string or Boolean values. case_insensitive If set to TRUE, the constant will be defined case-insensitive. Example: <?php define(\"EMAIL\", \"[email protected]\"); // Valid constant name echo EMAIL; // Displays \"[email protected]\" define(\"myCon\", true); if (myCon) { } // Evaluates to true define(\"ONECONSTANT\", \"some value\"); // Invalid constant name define(\"CONSTANT\", \"Hello world.\"); echo CONSTANT; // outputs \"Hello world.\" echo Constant; // outputs \"Constant\" and issues a notice. define(\"GREETING\", \"Hello world.\", true); 26 CU IDOL SELF LEARNING MATERIAL (SLM)

echo GREETING; // outputs \"Hello world.\" echo Greeting; // outputs \"Hello world.\" ?> 2.4DATA TYPES PHP has ten primitive types including four scalar types, four compound types, and two special types: Scalar types  bool  int  float  string Compound types  array  object  callable  iterable Special types  resource  null Scalar types A variable is a scalar when it holds a single value of the type integer, float, string, or Boolean. Integer Integers are whole numbers defined in the set {…-3, -2-, -1,0,1,2,3…}. The size of the integer depends on the platform where PHP runs. The constant PHP_INT_SIZE specifies the size of the integer on a specific platform. PHP uses the int keyword to denote the integer type. The following example illustrates some integers: <?php 27 CU IDOL SELF LEARNING MATERIAL (SLM)

$count = 0; $max = 1000; $page_size = 10; Code language: HTML, XML (xml) Float Floats are floating-point numbers, which are also known as floats, doubles, or real numbers. PHP uses the IEEE 754 double format to represent floats. Like other programming languages, floats have limited precision. PHP uses the float keyword to represent the floating-point numbers. The following example illustrates the floating-point numbers in PHP: <?php $price = 10.25; $tax = 0.08; Code language: HTML, XML (xml) Boolean Boolean represents a truth value that can be either true or false. PHP uses the bool keyword to represent the Boolean type. The bool type has two values true and false. Since keywords are case-insensitive, you can use true, True, TRUE, false, False, and False to indicate Boolean values. The following example shows how to assign Boolean values to variables: <?php $is_admin = true; $is_user_logged_in = false; Code language: HTML, XML (xml) When you use the values of other types in the boolean context, such as if-else and switch- case statements, PHP converts them to the Boolean values. PHP treats the following values as false:  The false keyword.  The integer 0 and -0 (zero). 28 CU IDOL SELF LEARNING MATERIAL (SLM)

 The floats 0.0 and -0.0 (zero).  The empty string (\"\", '') and the string “0”.  The empty array (array () or []).  The null.  The SimpleXML objects created from attributefewer empty elements. The values that are not one of these falsie values above are true. String A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“). For example: <?php $str = 'PHP scalar type'; $message = \"PHP data types\"; Code language: HTML, XML (xml) Compound types Compound data includes the values that contain more than one value. PHP has two compound types including array and object. Array An array is an ordered map that associates keys with values. For example, you can define a list of items in a shopping cart like this: <?php $carts = [ 'laptop', 'mouse', 'keyboard’]; Code language: HTML, XML (xml) The $carts array contains three string values. It maps the index 0, 1, and 2 to the value’s 'laptop', 'mouse', and 'keyboard'. The $carts is called an indexed array because it uses numeric indexes as keys. To access a value in an array, you use the square brackets: <?php echo $carts [0]; // 'laptop' 29 CU IDOL SELF LEARNING MATERIAL (SLM)

echo $carts [1]; // 'mouse' echo $carts [2]; // 'keyboard' Code language: HTML, XML (xml) Besides numeric indexes, you can use strings as keys for the array elements. These arrays are known as associative arrays. For example: <?php $prices = [ 'laptop' => 1000, 'mouse' => 50, 'keyboard' => 120 ]; Code language: HTML, XML (xml) To access an element in an associative array, you specify the key in the square brackets. For example: <?php echo $prices['laptop']; // 1000 echo $prices['mouse']; // 50 echo $prices['keyboard']; // 120 Code language: HTML, XML (xml) Object An object is an instance of a class. It’s a central concept in object-oriented programming. An object has properties. For example, a person object may have the first name, last name, and age properties. An object also has behaviours, which are known as methods. For example, a person object can have a method called getFullName () that returns the full name. Special types PHP has two special types: null and resource Null The null type has one one value called null that represents a variable with no value. 30 CU IDOL SELF LEARNING MATERIAL (SLM)

2.5 LOOPS PHP supports four types of looping techniques; I. for loop II. while loop III. do-while loop IV. foreach loop Let us now learn about each of the above-mentioned loops in details: for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These types of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter. Syntax: for (initialization expression; test condition; update expression) { // code to be executed } In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated. Steps are repeated till exit condition comes. Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1; Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10; Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2; Example: <?php // code to illustrate for loop 31 CU IDOL SELF LEARNING MATERIAL (SLM)

for ($num = 1; $num <= 10; $num += 2) { echo \"$num \\n\"; } ?> Output: 1 3 5 7 9 while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if it’s true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true. Syntax: while (if the condition is true) { // code is executed } Example: <?php // PHP code to illustrate while loops $num = 2; while ($num < 12) { $num += 2; echo $num, \"\\n\"; } ?> 32 CU IDOL SELF LEARNING MATERIAL (SLM)

Output: 4 6 8 10 12 do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program is executed as long as the condition holds true. Syntax: do { //code is executed } while (if condition is true); Example: <?php // PHP code to illustrate do...while loops $num = 2; do { $num += 2; echo $num, \"\\n\"; } while ($num < 12); ?> Output: 4 6 8 10 33 CU IDOL SELF LEARNING MATERIAL (SLM)

12 This code would show the difference between while and do…while loop. <?php // PHP code to illustrate the difference of two loops $num = 2; // In case of while while ($num! = 2) { echo \"In case of while the code is skipped\"; echo $num, \"\\n\"; } // In case of do...while do { $num++; echo \"The do...while code is executed at least once \"; } while ($num == 2); ?> Output: The code is executed at least once foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element. Syntax: foreach (array_element as value) { //code to be executed 34 CU IDOL SELF LEARNING MATERIAL (SLM)

} Example: <?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo \"$val \\n\"; } $arr = array (\"Ram\", \"Laxman\", \"Sita\"); foreach ($arr as $val) { echo \"$val \\n\"; } ?> Output: 10 20 30 40 50 60 Ram Laxman Sita 2.6 COMMENTS php comment syntax: single line comment While there is only one type of comment in HTML, PHP has two types. The first type we will discuss is the single line comment. The single line comment tells the interpreter to ignore 35 CU IDOL SELF LEARNING MATERIAL (SLM)

everything that occurs on that line to the right of the comment. To do a single line comment type \"//\" or \"#\" and all text to the right will be ignored by PHP interpreter. PHP Code: <?php echo \"Hello World!\"; // This will print out Hello World! echo \"<br />Psst...You can't see my PHP comments!\"; // echo \"nothing\"; // echo \"My name is Humperdinkle!\"; # echo \"I don't do anything either\"; ?> Display: Hello World! Psst...You can't see my PHP comments! Notice that a couple of our echo statements were not evaluated because we commented them out with the single line comment. This type of line commenting is often used for quick notes about complex and confusing code or to temporarily remove a line of PHP code. php comment syntax: multiple line comment Similar to the HTML comment, the multi-line PHP comment can be used to comment out large blocks of code or writing multiple line comments. The multiple line PHP comment begins with \" /* \" and ends with \" */ \". PHP Code: <?php /* This Echo statement will print out my message to the the place in which I reside on. In other words, the World. */ echo \"Hello World!\"; /* echo \"My name is Humperdinkle!\"; echo \"No way! My name is Uber PHP Programmer!\"; */ ?> Display: Hello World! 36 CU IDOL SELF LEARNING MATERIAL (SLM)

2.7 OUTPUTTING DATA TO THE BROWSER PHP provides the following methods for printing data in the browser: 1. print() 2. echo() 3. print_r() 2.7.1. print() This statement simply outputs to the browser. It's prototype looks as in: int print(argument) There is different typography for print () as in the following: 1. <?php print(\"Be a part of c-sharpcorner\");?> 2. <?php 1. $var=\"Be a part of c-sharpcorner\"; 2. print \"$var\"; 3. ?> Both of the preceding statements provide the same output, which is: Be a part of c-sharpcorner Technically it is not a function, it's a language construct. It always returns 1 regardless of the output. 2.7.2 echo () This is an alternative option to the print () statement. It just outputs the data to the browser without returning anything, like print(), and that is the main difference between print() and echo(). echo() is capable of outputting multiple strings. It's prototype can be written in the following manner: 1. void echo (string argument1, string argument2…., string argument n); Example 1. <?php 2. echo “Be a part of c-sharpcorner”; 3. ?> Example 37 CU IDOL SELF LEARNING MATERIAL (SLM)

1. <?php 2. $var1=\"hello\"; 3. $var2=\"how are \"; 4. $var3=\"you? \"; 5. echo $var1, \" Mr. \", $var2, $var3; 6. ?> The output is: Hello Mr. how are you? 2.7.3 print_r () It is an inbuilt function that is used in PHP to print or display the information stored in a variable. Basically, it prints human-readable information about a variable. If the variable is a string, integer or float, the value itself will be printed. If an array is given, values will be presented in a format that shows keys and elements. Similar notation is used for objects. Syntax: 1 print_r(variable, isStore) variable: It is a mandatory parameter that specifies the variable to be printed. isStore: It is an optional parameter which is of a boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. print_r() function will return the output which it is supposed to print if this parameter is set to TRUE. The below example demonstrates the usage of print_r in PHP. by printing string variable, integer variable and array: <?php $str = \"This is a string\"; //string $integ = 30;//integer $arra = array('0' => \"ashok\", '1' => \"sushma\", '2' => \"charan\");// array print_r($str); 38 CU IDOL SELF LEARNING MATERIAL (SLM)

echo \"<br>\"; print_r($integ); echo\"<br>\"; print_r($arra); ?> Output: 2.8 SUMMARY In programming, language constructs and built-in functions are often misinterpreted with one another due to the fact that both have more or less alike behavior. But they differ from each other in the way the PHP interpreter interprets them. Every programming language consists of tokens and structures which the respective language parser can recognize. So, whenever a file is parsed, the parser understands their usage and knows well what to do with them without having the need to examine them further. These tokens and structures are known as language construct. They are basically keywords that are a part of the programming language. In other words, they form the syntax of the language. 2.9 KEYWORDS  bool-Converting to Boolean ... To explicitly convert a value to bool, use the (bool) or (Boolean) casts  array-An array is a data structure that stores one or more similar type of values in a single value  object-Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable  variable-A variable must start with a dollar ($) sign, followed by the variable name. · It can only contain alpha-numeric character and underscore (A-z, 0-9, _). 39 CU IDOL SELF LEARNING MATERIAL (SLM)

 Syntax-syntax (/ˈsɪntæks/) is the set of rules, principles, and processes that govern the structure of sentences (sentence structure) in a given language, usually including word order. 2.10 LEARNING ACTIVITY 1. Write a program using for loop to print star pattern as: ___________________________________________________________________________ ___________________________________________________________________________ 2. Write a program to Print the sum of digits of a given number. ___________________________________________________________________________ ___________________________________________________________________________ 2.11 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain for loop. 2. Explain while loop. 3. Explain do while loop. 4. What is a variable? 5. Define constants. Long Questions 1. Create a script using a for loop to add all the integers between 0 and 30 and display the total. 2. Create a script to construct the following pattern, using a nested for loop. * ** 40 CU IDOL SELF LEARNING MATERIAL (SLM)

*** **** ***** ***** **** *** ** * 3. Difference between while and do while loop with example? 4. Write short note on all the loops 5. Write a PHP program to display colour names \"using foreach\" loop B. Multiple Choice Questions 1. Which loop evaluates the condition expression as Boolean, ifit is true, it executes the statements and when it is false it willterminate? a. For loop b. For each loop c. While loop d. All of these 2. Multidimensional arrays are simple arrays that have a. One dimensional b. Many arrays stored in them c. No indexes d. 1 element 3. Windows, Apache, MySQL, Perl, PHP, Python all of these arecategories in a. LAMP stack b. WAMP stack c. CAMP stack d. None of these 4. The basic syntax for calling a function is 41 a. function_name (experssion1, expersion2) b. (experssion1 : Function_name, expersion2 :Function_name) c. (experssion1, expersion2) CU IDOL SELF LEARNING MATERIAL (SLM)

d. None of these 5. Destruct ( ) function is used to call a a. Constructor b. Destructor c. Object d. Method Answers 1-c, 2-b, 3-b, 4-a, 5-b 2.12 REFERENCES Textbooks  T1: Steven Holzner, Wordpress-The Complete Reference, McGraw-Hill.  T2: Robin Nixon, WordPress-MySQL-JavaScript, O’Reilly. Reference Books  R1: Rasmus Lerdorf, Kevin Tatroe, Bob Kaehms, Ric McGrady, WordPress, O’Reilly, Shroff Publishers. 42 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 3: ARRAYS STRUCTURE 3.0 Learning Objectives 3.1 Introduction 3.2 Use of array 3.3 Types of Arrays 3.3.1 Numeric Array 3.3.2 Associative Array 3.3.3 Multi-Dimensional Array 3.4 converting between arrays and variables 3.5 Traversing arrays 3.6 Sorting 3.7 Summary 3.8 Keywords 3.9 Learning Activity 3.10 Unit End Questions 3.11 References 3.0LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe nature of arrays  Use of arrays  Defining types of arrays  Traverse between the arrays 3.1 INTRODUCTION Php array is an ordered map (consists of value on the basis of the key). It's far used to hold a couple of values of similar kind in a single variable. Gain of PHP array  Much less code: we don't need to outline multiple variables. 43 CU IDOL SELF LEARNING MATERIAL (SLM)

 Smooth to traverse: by means of the assist of a single loop, we will traverse all the elements of an array.  Sorting: we are able to sort the elements of the array. 3.2 USE OF ARRAY An array in Hypertext Preprocessor is simply an ordered map. A map is a type that pals values to keys. This type is optimized for several different makes use of; it could be treated as an array, list (vector), hash desk (an implementation of a map), dictionary, series, stack, queue, and possibly extra. As array values may be other arrays, bushes and multidimensional arrays are also possible 3.3 TYPES OF ARRAYS There is 3 unique sort of arrays and each array price is accessed using an identity that's referred to as array index. • Numeric of the listed array − an array with a numeric index. Values are saved and accessed in a linear way. • Associative array − an array with strings as an index. These stores detail values in affiliation with key values instead of in strict linear index order. • Multidimensional array − an array containing one or more arrays and values are accessed by the use of multiple indices. 3.3.1. PHP Indexed Array PHP index is represented with the aid of a range that starts from 0. We can store range, string, and item in the Hypertext Pre-processor array. All PHP array factors are assigned to an index variety via default. There are two approaches to define indexed array: 1st way: $season=array (\"summer season\",\" wintry weather \",\"spring\",\"autumn\"); 2nd manner: $season [0] =\"summer\"; $season [1] =\"wintry weather\"; $season [2] =\"spring\"; $season [3] =\"autumn\"; Example: <? 44 CU IDOL SELF LEARNING MATERIAL (SLM)

$season = array (\"Summer\", \"winter\", \"spring\", \"autumn\"); Echo \"Seasons are: “. $season [0]. \", \" . $season [1]. \", \". $season [2]. \" and “. $season [3]. \".\"; ?> Output: Season are: summer, wintry weather, spring, and autumn Example:2 <? $season [0] =\"summer\"; $season [1] =\"winter\"; $season [2] =\"spring\"; $season [3] =\"autumn\"; Echo \"Season are: $season [0], $season [1], $season [2] and $season [3]\"; ?> Output: Season are: summertime, winter, spring, and autumn 3.3.2. PHP Associative Array We can accomplice name with each array factors in personal home page the use of => image. There are ways to outline associative array: 1st way: $profits=array(\"sonoo\"=>\"350000\",\"john\"=>\"450000\",\"kartik\"=>\"200000\"); Second way: $earnings[\"Sonoo”] =\"350000\"; $revenue[\"John”] =\"450000\"; $earnings[\"Kartik”] =\"200000\"; Instance: <? $salary=array(\"Sonoo\"=>\"350000\",\"john\"=>\"450000\",\"kartik\"=>\"200000\"); Echo \"sonoo earnings: “. $revenue[\"Sonoo\"].\" \"; 45 CU IDOL SELF LEARNING MATERIAL (SLM)

Echo \"john salary: “. $income[\"John\"].\" \"; Echo \"Kartik salary: “. $earnings[\"Kartik\"].\" \"; ?> Output: Sonoo profits: 350000 John profits: 450000 Kartik salary: 200000 Example: <? $salary[\"Sonoo”] =\"350000\"; $salary[\"John”] =\"450000\"; $salary[\"Kartik”] =\"200000\"; Echo \"Sonoo salary: “. $salary[\"Sonoo\"].\" \"; Echo \"John salary: “. $salary[\"John\"].\" \"; Echo \"Kartik salary: “. $salary[\"Kartik\"].\" \"; ?> Output: Sonoo profits: 350000 John salary: 450000 Kartik income: 200000 3.3.3. PHP Multidimensional Array Multidimensional array is also called an array of arrays. It lets in you to store tabular records in an array. Hypertext Pre-processor multidimensional array can be represented in the shape of matrix that's represented by row * column. $emp = array 46 CU IDOL SELF LEARNING MATERIAL (SLM)

( Array(1,\"sonoo\",400000), Array(2,\"john\",500000), Array(3,\"rahul\",300000) ); In a multi-dimensional array, every detail in the primary array also can be an array. And every detail inside the sub-array can be an array, and so forth. Values in the multi- dimensional array are accessed using multiple indexes. Example: <? $emp = array ( array(1,\"sonoo\",400000), array(2,\"john\",500000), array(3,\"rahul\",300000) ); For ($row = zero; $row < 3; $row++) for ($col = 0; $col < 3; $col++) echo $emp[$row] [$col].\" \"; ?> Output: Sonoo 400000 John 500000 Rahul 300000 3.4 CONVERTING BETWEEN ARRAYS AND VARIABLES Offers two capabilities, extract () and compact (), that convert between arrays and variables. The names of the variables correspond to keys in the array, and the values of the variables emerge as the values inside the array. 47 CU IDOL SELF LEARNING MATERIAL (SLM)

For example, this array: $individual = array ('name' => 'fred', 'age' => 35, 'wife' => 'betty'); May be transformed to, or constructed from, these variables: $name = 'fred'; $age = 35; $spouse = 'betty'; The extract () feature mechanically creates nearby variables from an array. The indexes of the array factors are the variable names: Extract($person); // $call, $age, and $wife at the moment are set if a variable created with the aid of the extraction has the equal name as an existing one, the extracted variable overwrites the present variable. You could modify extract ()'s behavior by passing a 2d argument. Appendix a describes the feasible values for this second argument. The most useful price is extr_prefix_same, which says that the third argument to extract () is a prefix for the variable names which might be created. This helps make certain which you create unique variable names whilst you use extract (). It is right php style to always use extr_prefix_same, as proven right here: $form = \"spherical\"; $array = array (\"cowl\" => \"bird\", \"shape\" => \"square\"); Extract ($array, extr_prefix_same, \"book\"); Echo \"cover: $book_cover, e book form: $book_shape, form: $form\"; Cowl: fowl, book Form: square, form: spherical 3.5 TRAVERSING ARRAYS The most not unusual challenge with arrays is to do something with each detail—for instance, sending mail to every detail of an array of addresses, updating every report in an array of filenames, or including up each element of an array of prices. There are several approaches to traverse arrays in PHP, and the only one you pick out will depend upon your records and the task you're performing. The foreach construct 48 CU IDOL SELF LEARNING MATERIAL (SLM)

The maximum commonplace manner to loop over elements of an array is to apply the foreach construct: $addresses = array ('unsolicited [email protected]', '[email protected]'); Foreach ($addresses as $value) echo \"processing $valuen\"; Processing junk [email protected] Processing [email protected] Personal home page executes the body of the loop (the echo announcement) as soon as for each detail of $addresses in turn, with $cost set to the modern-day detail. Elements are processed by way of their internal order. An opportunity form of foreach gives you get right of entry to the current key: $individual = array ('name' => 'fred', 'age' => 35, 'spouse' => 'wilma'); Foreach ($man or woman as $okay => $v) echo \"fred's $ok is $vn\"; Fred's call is Fred Fred's age is 35 Fred's wife is Wilma in this example, the key for each element is positioned in $okay and the corresponding fee is placed in $v. The foreach construct does no longer functions on the array itself, however instead on a replica of it. You could insert or delete factors within the frame of a for each loop, safe in the understanding that the loop won't try to manner the deleted or inserted factors. The iterator capabilities Every PHP array maintains music of the modern-day element you're running with; the pointer to the present-day detail is known as the iterator. Hypertext Preprocessor has features to set, flow, and reset this iterator. The iterator features are: Cutting-edge( ) returns the detail presently pointed at by means of the iterator Reset( ) moves the iterator to the primary detail inside the array and returns it Subsequent( ) actions the iterator to the next element in the array and returns it Openprev () actions the iterator to the preceding element within the array and returns it End () movements the iterator to the last detail in the array and returns it Every () returns the important thing and cost of the present-day detail as an array and movements the iterator to the subsequent detail inside the array Key () returns the key of the cutting-edge detail The every () function is used to loop over the elements of an array. Its techniques elements in step with their inner order: 49 CU IDOL SELF LEARNING MATERIAL (SLM)

Reset($addresses); Even as (list ($key, $cost) = each($addresses)) echo \"$key is $valuen\"; 0 is [email protected] 1 is [email protected] This technique does no longer makes a copy of the array, as for each does. That is useful for very big arrays when you need to preserve reminiscence. The iterator capabilities are beneficial whilst you need to bear in mind a few components of the array one at a time from others. Instance indicates code that builds a desk, treating the first index and cost in an associative array as desk column headings. Example Constructing a table with the iterator functions $ages = array ('man or woman' => 'age', 'fred' => 35, 'barney' => 30, 'tigger' => 8, 'pooh' => forty); // begin table and print heading reset($ages); List ($c1, $c2) = each($ages); echo (“$c1 $c2n\"); // print the rest of the values while (list ($c1, $c2) = every ($a long time)) echo(\"$c1 $c2n\"); // quit the table echo (\" \"); Individual age Fred 35 Barney 30 Tigger 8 Pooh forty The use of a for loop If you recognize which you are handling an indexed array, in which the keys are consecutive integers starting at 0, you could use a for loop to depend on the indexes. The for loop operates at the array itself, no longer on a replica of the array, and methods elements in key order regardless of their internal order. Right, here's the way to print an array the use of for: $addresses = array ('junk [email protected]', '[email protected]'); For($i = 0; $i < count($array); $i++) $value = $addresses[$i]; echo \"$valuen\"; [email protected] [email protected] 50 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook