Skip to main content

What is Array in PHP?

 Now that, you know what arrays are? Let’s look at how to use them in PHP, starting with indexable arrays. All right. My opening PHP tags. On a comment here, indexable array. And let’s create that color array. So the array is going to have a name just like any other variable with a dollar sign first. So we’ll say colors, get, and then we’re going to use the keyword array and inside of the parenthesis for the array function or keyword, we’re going to have a comma-separated list of items. We’ll say, red, blue, and green. So if we want to see what this array looks like,

we can use a special function called print r. That will print the array nicely for us. So we’ll say print our colors. I’ll save this, and then I’ll go to the browser. And you can see that the array is a simple array with our indexes as numbers, starting at 0. That means that if we want to reference a specific color, we would do so by writing Echo, colors, square bracket, and then the index.
So if we wanted to print blue we would say Echo colors square bracket, 1 close square bracket. Now, if we go back out and refresh you can see the word blue shows up here. And if we wanted to have it on its own line, we can add some HTML.
So I will add single quotes. I’ll say, Echo, single quote paragraph, tag close single quote,
use our concatenation period, And then after colors, I’ll do the same thing. Single quote and
P tag. and now, Blue is on its own line. So that is an indexable array. Something that makes PHP
arrays, especially flexible. When compared to other programming languages is the way you define and add elements. While stricter languages require you to define a size when you define the array PHP. Does not. So we’ve defined our array up here with initial values, but if we want to add a new value, we could simply say colors. Square brackets with no index get and then whatever color we want to add. So let’s say yellow. Now if we print our array, And refresh the page. We have a brand new element with index 3.

So again, with stricter languages, you might have to say that you want an array of size 4, or you’d have to name the index here, which means that you need to keep track. Mentally of how many items are in your array PHP, makes this a little bit easier. Now, let’s look at a slightly more complicated example, with associative arrays. So let’s use that. Hometowns example. I’ll create a variable called hometowns. I’ll make it an array, but we want this to be an associative array. So, whereas with the indexable array, we only need to define the values. With an associative array. We need to define the keys as well. So I’ll say Joe, and then the arrow operator, this is how we assign values in arrays, so we’ll say, Joe Arrow operator. Middletown, New York, Aaron.

And then Westchester. Notice, we also have to put a comma after every key-value pair here as well. Dave & Eton. And Brian.
From Grand Rapids. Now, I’m also going to add a comma after the last element here. This is a perfectly valid syntax and it will make adding elements to the list. If we want to easier because we won’t have to remember to add this later. And again, let’s use print to visualize this. All right, so this looks a little bit more complicated. Let’s make this a little bit pretty to do that. We will Echo our
pre tags before and after print

00:05:00 Speaker 1
Great. That looks a lot nicer and you could see that the keys are the strings that we defined and the values are the values. So now if we want to print out, let’s say Dave’s Hometown we could say,
Echo will have an R P tag, dot hometowns and then we would need to reference the string index and its case sensitivity. So keep that in mind. We used a capital D for Dave, so we’ll say hometowns square bracket, Dave, and then we’ll close our P tag here. Now, if we refresh our page, it’ll say, Eaton PA. The last thing we’ll take a look at is a multi-dimensional array and to save some time. I’ve already pointed this out for you. It is a multi-dimensional array, where it has my brothers and me with various information about each of us. So we have our brothers variable gets array. And then the first key is my name. And the value is another array with key-value pairs for age job and state. If we want to show how this is visualized, we can again print out our pre-tag here. So we’ll say Echo Prix. Print is  Brothers. And then Echo and pre. Now, let’s go to that page.

So you could see the visualization looks very similar to the definition here and it looks familiar to the other arrays that we saw. But if we try to do something like for example, Echo, a key in the brother’s array, so we’ll say Echo pee. Brothers. Rob. we’ll save that if we go back to our browser,
You’ll see that we get an error here that says, notice array to string conversion and just the word array. That’s because we need to be more specific. Since Rob is a key that points to another array, we need to grab a key inside that second array to get the value. So if we want to get the state where Rob lives, we would need to add a second pair of square brackets here. So after the closing square bracket on Rob, we would open a square bracket at our quote And then grab the key to the second array. So we’ll say the state will close the square bracket will save. This will refresh and you can see the letters Florida show up. Here are the letters FL for Florida shows up here.
A raise will be a big part of working with data in your code and it’s good to get to know them as early as possible. Later,
you’ll learn how to easily Traverse through an array using loops.

Comments

Popular posts from this blog

Difference between loc() and iloc() in Pandas DataFrame

  Difference between loc() and iloc() in Pandas DataFrame Pandas library of python is very useful for the manipulation of mathematical data and is widely used in the field of machine learning. It comprises many methods for its proper functioning.  loc()  and  iloc()  are one of those methods. These are used in slicing data from the Pandas DataFrame. They help in the convenient selection of data from the DataFrame. They are used in filtering the data according to some conditions. The working of both of these methods is explained in the sample dataset of cars. loc()  :  loc()  is label-based data selecting method which means that we have to pass the name of the row or column which we want to select. This method includes the last element of the range passed in it, unlike  iloc() .  loc()   can accept the boolean data unlike  iloc()  .  iloc() :  iloc( )  is an indexed-based selecting method which means that we ...

Best digital marketing in Perth

Best digital marketing in Perth Introduction Your introduction into the brave new world of the digital space will be custom-tailored to your business needs requirements. You will be introduced to the crew who will be handling your project, from inception to the launch into the market. Assess It will be our job to not only know your customers but how they engage with the core products and  brand relationships . From here we break down what we research, to identify the core elements needed to engage the customer. Create It’s imperative that the design of your vessel is done right from the start. Its shape, level of focus, and attention to detail are crucial for a prosperous, lucrative, and extended journey. We will always present concepts and suggestions as per the requirement, but we truly believe this process should be a collaborative one between the creative crew of the PWD and the client. The final form will dictate its progression into the  development  and manufacturi...

Introduction to Transfer Learning

  Introduction to Transfer Learning We, humans, are very perfect in applying the transfer of knowledge between tasks. This means that whenever we encounter a new problem or a task, we recognize it and apply our relevant knowledge from our previous learning experiences. This makes our work easy and fast to finish. For instance, if you know how to ride a bicycle and if you are asked to ride a motorbike which you have never done before. In such a case, our experience with a bicycle will come into play and handle tasks like balancing the bike, steering, etc. This will make things easier compared to a complete beginner. Such leanings are very useful in real life as it makes us more perfect and allows us to earn more experience. Following the same approach, a term was introduced  Transfer Learning  in the field of machine learning. This approach involves the use of knowledge that was learned in some task, and apply it to solve the problem in the related target task. While most ...

What is the process of Data Analysis?

 Data analysis   is the process of collecting, cleansing, interpreting, transforming and modeling data to gather insights and generate reports to gain business profits. Refer to the image below to know the various steps involved in the process. Fig 1:  Process of  Data Analysis – Data Analyst Interview Questions Collect Data:  The data gets collected from various sources and is stored so that it can be cleaned and prepared. In this step, all the missing values and outliers are removed. Analyse Data:  Once the data is ready, the next step is to analyze the data. A model is run repeatedly for improvements. Then, the model is validated to check whether it meets the business requirements. Create Reports:  Finally, the model is implemented, and then reports thus generated are passed onto the stakeholders.

What is Copywriting? A Comprehensive Guide

  What is Copywriting? A Comprehensive Guide Introduction to Copywriting Copywriting is the art and science of crafting persuasive and compelling messages to promote a product, service, or idea. It's a vital component of marketing and advertising that can significantly impact a company's success. Whether through website content, social media posts, emails, advertisements, or any other medium, effective copywriting can capture attention, build trust, and drive action. The Importance of Copywriting In today's digital age, where consumers are bombarded with information from all directions, having clear and engaging copy is more critical than ever. Good copywriting can differentiate a brand, communicate its value proposition, and create a lasting impression on the audience. It’s not just about selling a product but also about building relationships and fostering loyalty. Historical Context Copywriting has evolved significantly since its inception. In the early days of print med...