How to create key value pair collection in php

0 votes
asked Jun 12, 2013 in Php by Robert

I am basically a C# guy and recently working in a small php website for my organization. I came across this question that, is there a way I can create key value pair collection in php sothing similar to what we have in C# as Hash Table or Dictionary etc? If so, please post me some sample code. Thanks in advance.

Share

1 Answer

0 votes
answered Jun 12, 2013 by administrator (315 points)
 
Best answer

In PHP, array itself can be used as key value pair collection. There are 2 ways you can access an array. One is the well know way, using index. But in php, you can also create array with key for each value. Below sample code may give you idea about how to create keyed array and how to access that.

$_Courses_Students = array("C#.net" => 45, "VB.NET" => 40, "ASP.NET" => 80);

In the above code, values given before "=>" is Key. other side is value

One thing to remember is that, if the array is created with Key value pair, then you may not be able to access the array items using index. So, you may not be able to use "for loop" to access those value. Use "foreach" loop.

foreach($_Courses_Students as $_Course => $_Student)
{
  //$Course will have key
  //$_Student will have value
}

To access the array value directly we can use the key like below, will print 45

echo $_Courses_Students["C#.NET"]

This key value pair array is also knows as Associative Arrays

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...