Handling Arrays and Strings in PHP

Last updated on May 31 2022
Aridam Das

Table of Contents

Handling Arrays and Strings in PHP

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

• Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
• Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>

  <body>

  

     <?php

        /* First method to create array. */

        $numbers = array( 1, 2, 3, 4, 5);

        

        foreach( $numbers as $value ) {

           echo "Value is $value <br />";

        }

        

        /* Second method to create array. */

        $numbers[0] = "one";

        $numbers[1] = "two";

        $numbers[2] = "three";

        $numbers[3] = "four";

        $numbers[4] = "five";

        

        foreach( $numbers as $value ) {

           echo "Value is $value <br />";

        }

     ?>

     

  </body>

</html>

This will produce the following result −

Value is 1 

Value is 2 

Value is 3 

Value is 4 

Value is 5 

Value is one 

Value is two 

Value is three 

Value is four 

Value is five 

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE − Don’t keep associative array inside double quote while printing otherwise it would not return any value.

Example

<html>

  <body>

     

     <?php

        /* First method to associate create array. */

        $salaries = array("mohammad" => 2000, "qadir" =>1000, "zara" => 500);

        

        echo "Salary of mohammad is ". $salaries['mohammad'] ."<br />";

        echo "Salary of qadir is ".  $salaries['qadir']. "<br />";

        echo "Salary of zara is ".  $salaries['zara']. "<br />";

        

        /* Second method to create array. */

        $salaries['mohammad'] = "high";

        $salaries['qadir'] = "medium";

        $salaries['zara'] = "low";

        

        echo "Salary of mohammad is ". $salaries['mohammad'] ."<br />";

        echo "Salary of qadir is ".  $salaries['qadir']. "<br />";

        echo "Salary of zara is ".  $salaries['zara']. "<br />";

     ?>

  

  </body>

</html>

This will produce the following result −

Salary of mohammad is 2000

Salary of qadir is 1000

Salary of zara is 500

Salary of mohammad is high

Salary of qadir is medium

Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.

<html>

  <body>

     

     <?php

        $marks = array(

           "mohammad" => array (

              "physics" => 35,

              "maths" => 30,​

              "chemistry" => 39

           ),

           

           "qadir" => array (

              "physics" => 30,

              "maths" => 32,

              "chemistry" => 29

           ),

           

           "zara" => array (

              "physics" => 31,

              "maths" => 22,

              "chemistry" => 39

           )

        );

        

        /* Accessing multi-dimensional array values */

        echo "Marks for mohammad in physics : " ;

        echo $marks['mohammad']['physics'] . "<br />";

        

        echo "Marks for qadir in maths : ";

        echo $marks['qadir']['maths'] . "<br />";

        

        echo "Marks for zara in chemistry : " ;

        echo $marks['zara']['chemistry'] . "<br />";

     ?>

  

  </body>

</html>

This will produce the following result −

Marks for mohammad in physics : 35

Marks for qadir in maths : 32

Marks for zara in chemistry : 39

PHP – Strings

They are sequences of characters, like “PHP supports string operations”.

NOTE − Built-in string functions is given in function reference PHP String Functions

Following are valid examples of string

$string_1 = "This is a string in double quotes";

$string_2 = "This is a somewhat longer, singly quoted string";

$string_39 = "This string has thirty-nine characters";

$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

<?php

  $variable = "name";

  $literally = 'My $variable will not print!\\n';

  

  print($literally);

  print "<br />";

  

  $literally = "My $variable will print!\\n";

  

  print($literally);

?>

This will produce the following result −

My $variable will not print!\n

My name will print!\n

There are no artificial limits on string length – within the bounds of available memory, you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in “this”) are preprocessed in both the following two ways by PHP −

• Certain character sequences beginning with backslash (\) are replaced with special characters
• Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are −

• \n is replaced by the newline character

• \r is replaced by the carriage-return character

• \t is replaced by the tab character

• \$ is replaced by the dollar sign itself ($)

• \" is replaced by a single double-quote (")

• \\ is replaced by a single backslash (\)

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator −

<?php

  $string1="Hello World";

  $string2="1234";

  

  echo $string1 . " " . $string2;

?>

This will produce the following result −

Hello World 1234

If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.

Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function

The strlen() function is used to find the length of a string.

Let’s find the length of our string “Hello world!” −

<?php

  echo strlen("Hello world!");

?>

This will produce the following result −

12

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function

The strpos() function is used to search for a string or character within a string.

If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.

Let’s see if we can find the string “world” in our string −

<?php

  echo strpos("Hello world!","world");

?>

This will produce the following result −

6

As you see the position of the string “world” in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

So, this brings us to the end of blog. This Tecklearn ‘Handling Strings and Arrays in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages​

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring
Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Handling Arrays and Strings in PHP"

Leave a Message

Your email address will not be published. Required fields are marked *