Dayana Benny Dayana Benny - 15 days ago 5
PHP Question

Store values of different arrays with same key in PHP

I stuck with my code and I am new to Php. How to store values of different arrays with same key in PHP ?.


for array 1: [0]=>31,[1]=>42, [2]=>21, .....

for array 2: [0]=>21,[1]=>21,[2]=>24, .....

for array 3: [0]=>45,[1]=>34,[2]=>45, ....


I tried to get a Output as :


[0]=>S5001:31,21,45|[1]=>S5002:42,21,34|[2]=>S5003:21,24,45.......[N]S50..N-1:21,23,45.


where S5001,S5002, are the keys of array1,array2,array3 ....

$student_marks_entered1=$this->input->post('mark1');
$student_marks_entered2=$this->input->post('mark2');
$student_marks_entered3=$this->input->post('mark3');
foreach($student_marks_entered1 as $key=>$value1)
{
$marks_arr1[]=$value1;
}
foreach($student_marks_entered2 as $key=>$value2)
{
$marks_arr2[]=$value2;
}
foreach($student_marks_entered3 as $key=>$value3)
{
$marks_arr3[]=$value3;
}


Desired Output is:

S5001:31,21,45|S5002:42,21,34|S5003:21,24,45.......S50..N-1:21,23,45

Answer

Use below code

<?php
$names = array( 0=>"S5001",1=>"S5002",2=>"S5003" );
$student_marks_entered1=array(31,42,21);
$student_marks_entered2=array(21,21,24);
$student_marks_entered3=array(45,34,45);

foreach($names as $key=>$name)
{
    $newArr[$key] = $name.":".$student_marks_entered1[$key].",".$student_marks_entered2[$key].",".$student_marks_entered3[$key];
}

$finalStr = implode("|", $newArr);
echo $finalStr;

Output:

S5001:31,32,33|S5002:42,44,46|S5003:21,23,25

Demo : Click Here