0

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"};
7
  • 3
    Which language you are using? Commented Oct 8, 2015 at 5:32
  • If you are using java, I would suggest you to use Map with key and corresponding to that key list of object as a value. Commented Oct 8, 2015 at 5:36
  • I mentioned in my question that I am using PHP. Commented Oct 8, 2015 at 5:39
  • Why is it required ?? Explain more.. Commented Oct 8, 2015 at 5:43
  • You should use two dimensional array Commented Oct 8, 2015 at 5:44

3 Answers 3

5

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";
Sign up to request clarification or add additional context in comments.

Comments

1

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";
    }
}

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.