How to create html array and access it in PHP or Javascript

When dealing with forms in html, sometimes you’ll want to ask for an array of inputs from the user. For example, you might want to ask user to select all their favorite hobbies.So how to read it from the user, in such a way that processing the data in php and javascript is a lot more easier?

The trick is to give the same name for all elements with square brackets [] at the end. So in the case of our first example, html code looks like:

Reading Swimming Chatting



Accessing array of data in PHP

PHP have already done the work for you. You just need to access the array $_POST[‘hobbies’]. You can process it as any other normal array.

Accessing array of data in Javascript

In javascript, you’ll first retrieve all the elements, then do as needed. In our case we’ll check whether each checkbox is checked and print it if checked. 

Also be careful not to use the for(..in..) loop because it loops over the properties and not values. If you are eager about what will happen if you use for..in.. loop, try it! and you’ll see what is printed out. 

If you’ve any questions or doubts, please refer it in comments below.

Leave a Reply

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