Aurea
Aurea

Reputation: 63

storing multiple values in same array with same index

If I want to add multiple values in array having same index in PHP, then can it be possible to create this type of an array? For e.g.,

fruits[a]="apple";
fruits[a]="banana";
fruits[a]="cherry";
fruits[b]="pineapple";
fruits[b]="grappes";

I want array to look like as below:-

fruits = {[a]=>"apple",[a]=>"banana",[a]=>"cherry",[b]=>"pineapple",[b]=>"grappes"};

Upvotes: 0

Views: 4543

Answers (3)

Amit
Amit

Reputation: 342

You cannot define multiple value under same key or index. In your case -

fruits[a]="apple";
fruits[a]="banana";

Here apple will be replaced by banana.

Instead, you may define array as -

fruits[a][] = "apple";
fruits[a][] = "banana";

Upvotes: 5

Vlk
Vlk

Reputation: 99

Edit: i updated my answer with php code, but i don't code php usually, this might not be the most optimal solution, i tried this code in a php sandbox

$subarray1[0] = "apple";
$subarray1[1] = "banana";
$subarray1[2] = "cherry";

$subarray2[0] = "pineapple";
$subarray2[1] = "grappes";

$fruits[0] = $subarray1;
$fruits[1] = $subarray2;

foreach( $fruits as $key => $value ){
    foreach( $value as $key2 => $value2 ){
        echo $key2."\t=>\t".$value2."\n";
    }
}

Upvotes: 1

Patel Kishan
Patel Kishan

Reputation: 65

use implode and explode .

subarray1[0] = "apple"
subarray1[1] = "banana"
subarray1[2] = "cherry"

subarray2[0] = "pineapple"
subarray2[1] = "grappes"

It is store data with ,(comma)

$ar="";
for($i=0;$i<=count(subarray1);$i++)
{
$ar[]=subarray1[$i];
}
$rt=implode(',',$ar);
 echo $rt;

It is Remove ,(comma) form array

$ex=explode(",",$ar);
print_r($ex);

Upvotes: 0

Related Questions