0% found this document useful (0 votes)
3 views14 pages

Chapter 8

The document provides an overview of arrays and strings in PHP, detailing the three types of arrays: numeric, associative, and multidimensional, along with their uses and how to manipulate them. It explains how to create and access these arrays, as well as the functions available for managing them, such as sorting and searching. Additionally, the document covers string handling, including the differences between single and double-quoted strings, string concatenation, and how to find the length of a string.

Uploaded by

rishigujrat25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Chapter 8

The document provides an overview of arrays and strings in PHP, detailing the three types of arrays: numeric, associative, and multidimensional, along with their uses and how to manipulate them. It explains how to create and access these arrays, as well as the functions available for managing them, such as sorting and searching. Additionally, the document covers string handling, including the differences between single and double-quoted strings, string concatenation, and how to find the length of a string.

Uploaded by

rishigujrat25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
ARRAY AND STRING eo imilar type of values in a single value. For ‘An array is a data structure that stores one or more si example, if you want to store 100 numbers, then instead of defining 100 variables, it is easy to define an array of 100 length, Arrays in PHP are flexible and can hold elements of any type, including other arrays, making them suitable for creating multidimensional arrays. PHP provides a rich set of functions for working with arrays, such as sorting, filtering, and manipulating array clements. Arrays are fundamental for organizing data and implementing various data-driven functionalities in PHP applications, There are three different kind of arrays and each array value is accessed using an ID. ic index, Values are stored and accessed in linear © Numeric array - An array with a numeri ry where fashion. In PHP, a numeric array, also known as an indexed array, is a type of array the elements are accessed using numeric indices, which are automatically assigned starting from 0. This type of array is useful for storing and managing a list of items where the order matters or when elements are similar in nature. The indices of numeric arrays are integer values, and PHP handles them automatically if not explicitly specified. Numeric arrays are ideal for scenarios where you need to access elements sequentially or perform operations that rely on the position of elements, such as iterating through a list of values. PHP provides various functions to manipulate numeric arrays, including sorting, searching, and modifying elements. These arrays offer a straightforward way to manage ordered collections of data, making them a fundamental part of PHP programming. : ‘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. In PHP, an associative array is a type of array where each element is accessed using a named key rather than a numeric index. These keys are user-defined strings or integers that provide a meaningful way to index and retrieve values. Associative arrays are ideal for scenarios where the relationship between data elements is more descriptive than numeric indexing allows. For instance, you might use associative arrays to represent records with fields like "name," "age," and "email," where each key corresponds to a specific attribute of the data. PHP offers various functions to manipulate associative arrays, including retrieving, updating, and iterating over key-value pairs, making them a powerful tool for managing complex data structures and improving code readability Multidimensional array - An array containing one or more arrays and values are accessed using multiple indice, a multidimensional array is an array that contains one more arrays as its elements, This allows for the creation of complex data structures, 163 184 ISHAN’S Wab Technologies ‘hete arrays are nested within other arrays to represent hierarchical ot gridvlke data, ‘Multiimensional arays can be used to store and manage data that has multiple levels ‘of relationships, such as matrices table, or records with nested attributes, NUMERIC ARRAY {tis also called indexed array because ench element of aray is assigned with an index nomber, Index number stats form 0. Index number is enclosed within () ie. Sfruits[0}, Struts, Sfruits(2} and so on. There are two ways to assign the valves to the array. 4) Using array function : It is an builtin function to create an array with assigned values, Index can be assigned automatically. ‘fruits = aray("Apple*, ‘Banana’, "Mango", “Orange”) ; ‘Using index aumber: In this method array is created by assigning values to each index ‘oumber, Struts{0)="Apple”; Sfruis[1]="Banan: Sfruits[2]+"Mango’ Sfruits(3]~"Orange”. » (Geacrally a oop is used to access all the elements of en aray. A buil in function array count) ‘will return the total no of elements inthe array (length ofthe array) ‘ ‘tite>Loop to display indexed array in PHP<(tie> “

Accessing array using for loop

"18", "Harsh"=>"18", "Abhay"=>"20"), ‘eres the second way to create associative arays in PHP: Sagef Anoop] = "18" ‘

Associtive Amay using named keye

186 “"18", "Harsh"=>"19", ISHAN'S Web Technologas 167 gp ShOTANOOD". Saget Anoop." yea : echo "
"; e Intl ctor | cht Associative Array using named keys ‘Anoop 18 years old. Loop to display Associative Arrays “To access all the elements of an associative array foreach loop is used. The following example shows this. ‘ctile>Loop to display associative array ‘=h2> foreach to access all the elements of associ "18","Harsh"=>"19", “Abba foreach(Sage as $x => Sx_value) foreach to access all the elements of associ Neme=Ancop, Age™I8 NamerHarsh, Age=19 Name=Abliy. ‘A multidimensional array each element in the msin array can also be an array. And each element in the sub-aray can be an array, and so on. Values in the mul-dimensional array are accessed sing multiple index. Lets look at the following example where we create a two dimensional aray to store marks of tvee students in three subjects ‘hint ‘PHP Multidimensional Aray Examplecttile> boy ‘uray and Sting output, 08 ISHAN'S Wob Tachnologiog ‘Multidimensional Array army "Physica" => 89, "Maths" => 93, "Chemisty" 88 oy “Harish” => array( "Physics" => 91, ats" ~> 94, "Chemisty" => 96 » Anil” > aray( "Physics" => 86, "Maths" => 65, "Chemistry" => 90 ) 1 accessing multidimensional array in PEP echo ""; echo "NamePhysiesMaths Chemistry "; ‘echo "t~Amit/td>" Smarks['Amit] (Physics! "", ‘Smarks{'Amit|[Maths!."~" Smarksl'Ami] Chemistry)."Harish * Smarks[ Harsh Physica). "cid>" ‘Smarks[‘Harish'][ Maths).** Smarks[ Harish] Chemistry "" echo " Anil ~" Smarks['Anil {Physics "", ‘Smarks{‘Anil][Maths)."* Smarks[Ani (Chemisty). ""; echo "" hi floes eeenne Multidimensional Array me Physic) Matha Chemie it foo__ 23a, rier Jo [96 i fos] _J90 ere is an another multidimensional example to print a matrix of 3 rows and 3 cols. Sim tead> ‘citle> PHP Multidimensional Array Example ‘ /Multidimensional Array/h2> ‘ Ti fen tetas true oerwie returns fe, Fores: toh Jroamay('Volvo"=>°XC907BMW"=>"X5"%, Multidimensional Array : : | 3340 22750 234530 & " a s Array Functions * count 4 ‘This funetion returns the no of elements in an array iM Fore ‘ \ { echo "Key exists"; ) else ( ‘echo "Key does not exist!"s ‘ iftrray_Key_exists("Volvo" $2) tue is exists into an array or not Ifthe given value exists into it returns [Link] search i case-sensitive, Glenn”, "Clevelant m Output Match found array_keysOr= ‘This function retums al the keys of an array into an another array. ISHAN'S Web Technologies 173 ‘amy and String orgs {nto an another array verge() function merge two array and return the result int ‘ For ex: "XC90,"BMW"="X5"); ear selee: ‘Skeymaray_hey(S0 | | sxaeamy(rbue, yellow foreach $key a8 $x) ( |] sasearry_merge($a,$02); echo "Key= Sx; forench( $13 a8 Sx) echo "b>"; ql ) | | estos | echo ""; 2: | utp Key= Volvo i Key= BMW | array_valuesQs | ea Tain Shea) esc aa by cnn els oo | aie | : |} repo Eee + | this fnetion delete the lst element of an ara. "Peter,"Age"=>"4","County"=>"USA"); h ad ‘Sb=array_values($a); SN ; ° a ee , |) | | Seraraycrea’ "green" "blue foreach(Sb as $x) ! ary pop(Ss)s { foreach(Sa as $x) ‘echo Sx; | { ‘echo "
"; i echo $x; echo "
5 1 ISHAN'S Web Technology say ana sing | out Quiput, Volvo red | BMW green Toyota array_push(s array searehO'> soe auray_push( function ads one or more values atthe end of an array. Tie aay,searchO foetin search an aay fora value and Forex: Forex ‘"bh 5 Ba Srraray('s"=>"red","b"=>"green,e%-0" ree eee tech array_search("red" $a); aray_push(Sa,"blue "yellow"; foreach(Sa as Sx) exho Sx; | echo" | : blue yellow ray_reverse(:- “The array_reverse() function returns an array inthe reverse order Forex: "; y > ‘Sararray("a"=>"Volvo',"b"=>"BMW""c"=>"Toyota"); SortO:- Sori( fimction sorts the elements ofthe aay in ascending order Forex: php ‘Stts-aray(*Apple”,"Orange’,"Banans"); sort(Sfruits); Slength-count(Sfruits); fox($x=0;Sx “litle>How to find length of any string in PHP 7/tile> Szlenfunctions2> Iutml> wTUuewvvwrv:r * =P 179 ome Str_word_count function ‘Tota word present in tring = 5 Reverse String In PHP. ‘To reverse a string in PHP, use a function named strrev0. This function reverses a string in PHP. Here is an example: tead> “itle>reverse string in PHP steey functions php String var= "Hello"; Sting reverse = surew(Sstring_ ya‘); ‘echo "Reverse of string: " Ssting_var." will bech>*; echo Ssting reverse; 180 Outpy strrev function Reverse of string: Hello will be lle ‘Search for Specific Text within String in PHP To search for the specific text present in the string in PHP, then use a function named strpos) ‘This function searches for a specific text within the string. In case, if'a match is found, then the function returns the character's position of the first match. ‘And if'no match is found, then it will retun FALSE. Here is an example searches for the text “world” inthe string "Hello World!, This is PHP": “ttle search for specific text within stringitile> strops function "; ) if(Stind_codes) ‘echo "Codes is at position: "-$find_codes; ‘echo "
"; ) if(Sfind_is) is at position: " Sfind_is echo "
"; stops function Worlds at position: 6 iain at portion: 16, 104 fa ISHAN'S Web Technologeg Replace Text within String in PHP Zo replace text within sting in PHP, then use a function named st_replaceQ). This function replaces some characters with some other characters in the string in PHP. Here is an example, replaces the text ae ar eran replace text within string ‘ ‘str_replace function ‘The example code on finding and replacing any specific/particular text within any string in PHP, Output str_replace function Iipst lve to read everything ray and Sting ‘changing ease of Text within string ‘Fo enange the case of text within string in PHP, then use the following functions: (a), Sttoupper: To Convert string into capital letters ©) Sirolower : To Conver string into small letters (© Uefrst: To Conver first letter of string into Capital letters ‘The following example shows the above three functions. - Changing case of text within string ”; echo “UC case: “uefirst(Snew_string); > tata Change case functions Lower cate: ilove web desinging Upper nse : [LOVE WEB DESINGING UC care I Love Web Desinging 103 ue ISHAN'S Web Technologies ‘Some Other String Functions chunk spilt ‘The chunk. splitQ function splits a string into a series of smaller pars, Syntax chunk_split([Link] end) Here: ‘Sering:- Specifies the string o split ‘Length:- A number that defines the length ofthe chunks. isan optional Parameter. End: A string that defines what to place atthe end ofeach chunk. It is an optional Parameter. For Ex Sringl:-Specites te first string to compare Strng2:-Specifes the second string 1 compare For Ex:- 187 ray and Sting out hello world stetoupperO : ‘Te strtoupperO fiction conversa string into upper ease string. - Que HELLO WORLD subst The subst foetion retusa past of sting Syntax substr(sering start ength) Bere Stringl-Speciies the string from which we want to get a substring, Start-Specifies where to startin the string Length:- Specifies the length ofthe retuned string. It is an optional parameter -Qutput, For Ex:- 2 ‘ f oe ISHAN’S Web Technologies | | EXERCISDD |. Veny Sort AnsweR TyPE QUESTIONS: Qa. What isan array? i An array isa data stuetire that stores one or more similar type of values in a single value, Y ! Ans, 22. How many types of array avallable in php? f ns: There ar thes iferent kind of arays and etch ary vl is acessed using an ID. ’ Q3. Write the name of diferent types of arrays? ; ‘Ans: + Namerie array ~ An aray with a numeri index. Values are stored and accessed linear fashion ‘ * Associative array ~ An array with stings a index, This stores clement values in ; association with key values rather than in a strict linear index order. ‘ + Multidimensional erray ‘ 4. What is oumeric array? : fae Mato called indexed army tena each element of aay is assigned with an index 6 umber. QS. Whatis associative array? : Ans Aercitive ays fn PHP, are amas that ss named eyo igs that you esign to ’ tem SS Whe oo is sed races athe clement of an associative array? a Ans. For-eah loop. 4 7. What is multidimensional array? ‘Ans. A multi-dimensiona array each elemeat in th rain aay can also be an array. And each clement inthe sub-array can be an aray, and so on, ‘Whieb fanetion is used to count the no. of element is array. Count Q9. Whats the use of array_keys Q functions? Gas. This funtion rus all the keys of an aray into an another aay, Q.10. What isthe use of array merge Q function, ‘Ans. array_merge() function merge two array and return the result Q.11. Which function Is use fo delete the las element of array? Ans. popQ Q2, Whats the use of array search ( function? ‘Ans. The aray_search() function search an array fora value and retums the Key, Q43. What isa string? Ans Strings are basically a sequence of characters such as "am sng! php strings", "strings", ete, Qs. Ans. 0 an another array ello world", "hello 1 sor aie Haske got ng eee? Ame IPA ution ius fo reverse astig? et wea ects feo feces ett BI oe (Spr TC a a (0 Unit To Conver tater of elo ie Cai es Il. SHORT ANSWER TYPE QUESTIONS: 1. Whatis ary? With pes of amy ia PHP. 3 tw youl ration lj f ajerel mat apot wea em tagt II. LONG ANSWER TYPE QUESTIONS: type with lable camp wet sagt eis sd Sein PPT ooo

You might also like