What is an Array & its cases to use in PHP?

Posted by

arrays is a type of data structure that allows us to store multiple elements of similar data type under a single variable. the arrays are helpful to create a list of elements of similar data types, which can be accessed using their index number.

In simple words (array is a special variable, which can hold more than one value at a time).

example: assume we want to store five names and print them accordingly. this can be easily done by the use of five different string variables. but instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. here array comes to helps us to store every element within a single variable and also allows easy access using an index number. an array is created using with an array()function in PHP

Cases to use array in php

case1

<?php  
  $subjects=array("c++","php","java","os");  
    echo " subjects: $c++[0],$php[1],$java[2],$os[3]";  
?>  

output

subjects: c++,php,java,os

case2

<?php  
     $subjects[0]="c++";  
     $subjects[1]="php";  
      $subjects[2]="java";  
      $subjects[3]="os";  
      echo "subjects: $c++[0],$php[1],$java[2],$os[3]";  
?>  

output

subjects: c++,php,java,os

case3

<?php    
    $marks=array("c++"=>"24","php"=>"56","java"=>"77");    
   echo "c++: ".$marks["c++"]."<br/>";  
    echo "php: ".$marks["phpjava"]."<br/>";  
    echo "java: ".$marks["Kartik"]."<br/>";  
?>    

output

c++:24
php:56
java:77

case4

<?php    
    $marks["c++"]="24";    
    $marks["php"]="56";    
    $marks["java"]="77";    
   echo "c++  ".$marks["c++"]."<br/>";  
   echo "php  ".$marks["php"]."<br/>";  
   echo "java  ".$marks["java"]."<br/>";  
?>   

output

c++  24
php  56
java  77
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x