Associative array in php

Associative array in php
Associative array in PHP


Associative array-

The associative arrays is similar to numeric arrays in term of functionality, but they are different in term of index. The index assigned to values can be arbitrary and user defined strings. And don't keep associative array inside double quote while printing otherwise it would not return any value.

Example-

In this example showing how to create and access numeric indexed array. In this example we have used array() function to create array. And here we have explain array index and array value.

<!DOCTYPE html>
<html>
<head>
            <title>Associative array</title>
</head>
<body>
            <?php
                        //Create array
                        $data = array('dharmveer' => 98, 'veer'=>90, 'monu'=>99, 'mona'=>100);
                        //Access array directly
                        echo $data['dharmveer']."<br>";
                        echo $data['veer']."<br>";
                        echo $data['monu']."<br>";
                        echo $data['mona']."<br>";

                        //Access array using loop
                        foreach ($data as $key => $value) {
                                    echo "Index is ".$key."<br>";
                        }

                        //Access array using loop
                        foreach ($data as $key => $value) {
                                    echo "Value is ".$value."<br>";
                        }
            ?>
</body>
</html>

Output-

Example-

In this example showing how to create and access numeric indexed array. In this example we have not used array() function to create array and here array create and access manually. And here we have explain array index and array value.

<!DOCTYPE html>
<html>
<head>
            <title>Associative array</title>
</head>
<body>
            <?php
                        //Create array manually
                        $data['dharmveer'] = 98;
                        $data['veer'] = 90;
                        $data['monu'] = 99;
                        $data['mona'] = 100;
                        //Access array directly
                        echo $data['dharmveer']."<br>";
                        echo $data['veer']."<br>";
                        echo $data['monu']."<br>";
                        echo $data['mona']."<br>";

                        //Access array using loop
                        foreach ($data as $key => $value) {
                                    echo "Index is ".$key."<br>";
                        }

                        //Access array using loop
                        foreach ($data as $key => $value) {
                                    echo "Value is ".$value."<br>";
                        }
            ?>
</body>
</html>

Output-

Post a Comment

0 Comments