Mixed Associative Arrays

Hi,
I found some associative arrays having no keys. I can’t understand the purpose of such arrays. What we call them? How we delete and add elements in such arrays? Kindly explain. I have got an example program below:

<?php 
/* associative arrays without keys */ 
$array1 = array("color"=>"red",2,4); 
$array2 = array("a","b","color"=>"green","shape"=>"trapezoid",4); 
 
foreach($array1 as $value) 
   echo "$value <BR>"; 
 
foreach($array2 as $value) 
   echo "$value <BR>"; 
?>

Following is the output:

red
2
4
a
b
green
trapezoid
4

Try the following script which shows more information:

echo ‘<pre>’; // adds line feed 
print_r($array1);

var_dump($array2);

echo ‘</pre>’;
1 Like

I have to comment the echo statements, otherwise no output was displayed. The output given below was really useful:
red
2
4
a
b
green
trapezoid
4

Array ( [color] => red [0] => 2 [1] => 4 ) array(5) { [0]=> string(1) “a” [1]=> string(1) “b” [“color”]=> string(5) “green” [“shape”]=> string(9) “trapezoid” [2]=> int(4)

The last 2 lines of the output tell me the indexes associative with non-keyed elements which is very useful.

}

I think the blank screen was due to posting from a Tablet and selecting incorrect quotation marks. Try replacing with single or double quotation marks because it does make it a lot easier to see the parameters.

Long and the short is that any element added to any array without a key is assigned the next numerically valid number as a key.

Associative arrays can have numerically indexed elements.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.