Array in PHP

Array in PHP

Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.

A PHP array is a variable that stores more than one piece of related data in a single variable.

Think of an array as a box of chocolates with slots inside.

The box represents the array itself while the spaces containing chocolates represent the values stored in the arrays.

The diagram below illustrates the above syntax.

Numeric Arrays

Numeric arrays use number as access keys.

An access key is a reference to a memory slot in an array variable.

The access key is used whenever we want to read or assign a new value an array element.

Below is the syntax for creating numeric array in php. Array Example

<?php
$variable_name[n] = value;
?>

Or

<?php
$variable_name = array(n => value, …);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let’s now look at an example of a numeric array.

Suppose we have 5 movies that we want to store in array variables.

We can use the example shown below to do that.

<?php

$movie[0] = 'Shaolin Monk';
$movie[1] = 'Drunken Master';
$movie[2] = 'American Ninja';
$movie[3] = 'Once upon a time in China';
$movie[4] = 'Replacement Killers';

?>

Here,

Each movie is given an index number that is used to retrieve or modify its value. Observe the following code-

<?php
$movie[0]="Shaolin Monk";
$movie[1]="Drunken Master";
$movie[2]="American Ninja";
$movie[3]="Once upon a time in China";
$movie[4]="Replacement Killers";
echo $movie[3];
$movie[3] = " Eastern Condors";
echo $movie[3];
?>

Output:

Once upon a time in China Eastern Condors

As you can see from the above examples, working with arrays in PHP when dealing with multiple values of the same nature is very easy and flexible.

Alternatively, the above array variables can also be created using the following code.

<?php
$movie = array(0 => "Shaolin Monk",
1 => "Drunken Master",
2 => "American Ninja",
3 => "Once upon a time in China",
4 =>"Replacement Killers" );
echo $movie[4];
?>

Output:

Replacement Killers
PHP Associative Array

Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.

Below is the syntax for creating associative array in php.

<?php
$variable_name['key_name'] = value;

$variable_name = array('keyname' => value);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “['key_name']” is the access index number of the element
  • “value” is the value assigned to the array element.

 Let’s suppose that we have a group of persons, and we want to assign the gender of each person against their names.

We can use an associative array to do that.The code below helps us to do that.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");
print_r($persons);
echo "";
echo "Mary is a " . $persons["Mary"];
?>

 HERE,

Output:

Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

Associative array are also very useful when retrieving data from the database.

The field names are used as id keys. 

PHP Multi-dimensional arrays

These are arrays that contain other nested arrays.

The advantage of multidimensional arrays is that they allow us to group related data together.

Let’s now look at a practical example that implements a php multidimensional array.

The table below shows a list of movies by category.

The above information can be represented as a multidimensional array. The code below shows the implementation.

<?php
$movies =array(
"comedy" => array("Pink Panther", "John English", "See no evil hear no evil"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"Romance" => array("Romeo and Juliet")
);
print_r($movies);
?>

 HERE,

Output:

Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => See no evil hear no evil ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array ( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

Another way to define the same array is as follows

<?php
$film=array(

                "comedy" => array(

                                0 => "Pink Panther",

                                1 => "john English",

                                2 => "See no evil hear no evil"

                                ),

                "action" => array (

                                0 => "Die Hard",

                                1 => "Expendables"

                                ),

                "epic" => array (

                                0 => "The Lord of the rings"

                                ),

                "Romance" => array

                                (

                                0 => "Romeo and Juliet"

                                )

);
echo $film["comedy"][0];
?>

Output:

Pink Panther

 Note: the movies numeric array has been nested inside the categories associative array 

PHP Arrays: Operators

PHP Array Functions

Count function

The count function is used to count the number of elements that an php array contains. The code below shows the implementation.

<?php
$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");
echo count($lecturers);
?>

Output:

3

is_array function

The is_array function is used to determine if a variable is an array or not. Let’s now look at an example that implements the is_array functions.

<?php
$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");
echo is_array($lecturers);
?>

Output:

1

Sort

This function is used to sort arrays by the values.

If the values are alphanumeric, it sorts them in alphabetical order.

If the values are numeric, it sorts them in ascending order.

It removes the existing access keys and add new numeric keys.

The output of this function is a numeric array

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

sort($persons);

print_r($persons);
?>

Output:

Array ( [0] => Female [1] => Female [2] => Male )

ksort

This function is used to sort the array using the key. The following example illustrates its usage.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

ksort($persons);

print_r($persons);
?>

Output:

Array ( [John] => Male [Mary] => Female [Mirriam] => Female )

asort

This function is used to sort the array using the values. The following example illustrates its usage.

<?php

$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

asort($persons);

print_r($persons);

?>

Output:

Array ( [Mary] => Female [Mirriam] => Female [John] => Male )

Why use arrays?

  • Contents of Arrays can be stretched,
  • Arrays easily help group related information such as server login details together
  • Arrays help write cleaner code.
Summary
  • Arrays are special variables with the capacity to store multi values.
  • Arrays are flexibility and can be easily stretched to accommodate more values
  • Numeric arrays use numbers for the array keys
  • PHP Associative array use descriptive names for array keys
  • Multidimensional arrays contain other arrays inside them.
  • The count function is used to get the number of items that have been stored in an array
  • The is_array function is used to determine whether a variable is a valid array or not.
  • Other array functions include sort, ksort, assort etc.

Thanks For Visiting, Keep Visiting

Further reading

☞ PHP for Beginners - Become a PHP Master - CMS Project

☞ Learn Object Oriented PHP By Building a Complete Website

☞ MEVP Stack Vue JS 2 Course: MySQL + Express.js + Vue.js +PHP

☞ Object Oriented PHP & MVC

☞ PHP OOP: Object Oriented Programming for beginners + Project

☞ Learn PHP Fundamentals From Scratch

☞ The Complete PHP MySQL Professional Course with 5 Projects

☞ The Complete JavaScript Course 2019: Build Real Projects!


This post was originally published here

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Which is the best PHP Web Development Company in India?

Which is the best PHP Web Development Company in India?

Many experienced players prefer to give it a go ahead with PHP for their web development needs because of the simplicity that PHP provides. PHP is loaded with features that many other languages lack and those pre-defined features can bring new functionalities and finishing touch to your existing or new website that you are looking forward to create. Wouldn’t it be great to get the best PHP Web Development Company for your project; we have a reputation as few of the leading firms in IT industry when it comes to PHP development.

Perks you should keep an eye out for before considering to outsource project to any web development company:

1. Company’s Reputation- It is very important to know about the previous projects that the company has delivered and the success rate of those products. You can visit company’s website for client testimonials or can google reviews given to them by genuine clients. We follow transparency, you can contact our previous clients and let them tell you how their experience was while working with us.

2. Technical Skill set and Expertise- You should select a company that has multiple resource pool of expert and technically sound developers. Our developers are experienced with different PHP frameworks and are exceptionally good with writing bug free codes. You can also hire PHP developer in India from us, as our developers have on hand experience in PHP development (core and frameworks)

3. The Budget- Costing has always played as one of the most important roles in every business deal. We provide competitive pricing with no hidden cost guaranteed. With us you can expect your project to be in best quality with no compromise to be made even with the best price in the market.

Why Data EximIT is the best PHP web development company in India?

Here are some of the features that might love about Data EximIT:

 Reputation of Data EximIT is wonderful among the previous clients.

 We have around 87% of retention ratio of clients.

 We were time committed, means every milestone was achieved before or on time.

 Data EximIT follows Agile development so it was the best possible methodology.

 We have huge team with different expertise over multiple PHP frameworks, so you are provided with ample to options to choose from.

 We are very active in communication part. Method or time of communication was never an issue at Data EximIT.

 We have some of the best designers to ensure that your project not only functions but also looks and feels fabulous.

 We provided customers with best costing without compromising on the quality at all.

 We also provide dedicated PHP developer or team of PHP developers on hire for your project.

Data EximIT is where customers feel confident to come up with idea and leave with fully functioning & best in quality projects. You can also avail our developers at your requested site location if you decide to hire PHP developers in India from us.

Feel free to contact our experts and let success reach you by working with the best PHP web development company.