What Types of Data Can Be Used as Array Keys?

deepak singh
Posts: 686
Joined: Fri Sep 30, 2016 4:19 pm

What Types of Data Can Be Used as Array Keys?

Postby deepak singh » Sat Oct 01, 2016 5:19 pm

What Types of Data Can Be Used as Array Keys?

rameshkhd
Posts: 1279
Joined: Sun Aug 28, 2016 10:45 am

Re: What Types of Data Can Be Used as Array Keys?

Postby rameshkhd » Sat Oct 01, 2016 5:19 pm

Two types of data can be used as array keys: string and integer. When a string is used as a key and the string represent an integer, PHP will convert the string into a integer and use it as the key. Here is a PHP script on different types of keys:
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
print("Array with mixed keys:\n");
print_r($mixed);
print("\$mixed[3] = ".$mixed[3]."\n");
print("\$mixed[\"3\"] = ".$mixed["3"]."\n");
print("\$mixed[\"\"] = ".$mixed[""]."\n");
?>
This script will print:
Array with mixed keys:
Array
(
[Zero] => PHP
[1] => Perl
[Two] => Java
[3] => C+
[] => Basic
)
$mixed[3] = C+
$mixed["3"] = C+
$mixed[""] = Basic
Note that an empty string can also be used as a key


Return to “PHP”

Who is online

Users browsing this forum: No registered users and 3 guests