How to push a value based on matched value in PHP ?
In PHP, to push the value in an array on match we need an array with key and value pair. An array which contains key and value pair is known as associative array.
Approach: Create two different associative array named as array1 and array2. Then compare the value of array1 with the key of array2 and if we get a match then we will push a static key and value pair as follows:
Program 1:
<?php
$array1 = [
"GFG1" => "1" ,
"GFG2" => "2" ,
"GFG3" => "3"
];
$array2 = [
"1" => [ "Subject" => "HTML" ],
"2" => [ "Subject" => "CSS" ],
"3" => [ "Subject" => "JavaScript" ]
];
foreach ( $array1 as $key1 => $value1 ) {
foreach ( $array2 as $key2 => $value2 ) {
if ( $key2 == $value1 ) {
$array2 [ $value1 ][ "Organization" ]
= "GeeksforGeeks" ;
}
}
}
print_r( $array2 );
?>
|
Output:
Array
(
[1] => Array
(
[Subject] => HTML
[Organization] => GeeksforGeeks
)
[2] => Array
(
[Subject] => CSS
[Organization] => GeeksforGeeks
)
[3] => Array
(
[Subject] => JavaScript
[Organization] => GeeksforGeeks
)
)
In the above program, the value is pushed in an existing array. If you want to push value in a whole new array then see the below program.
Program 2:
<?php
$array1 = [
"GFG1" => "1" ,
"GFG2" => "2" ,
"GFG3" => "3"
];
$array2 = [
"1" => [ "Subject" => "HTML" ],
"2" => [ "Subject" => "CSS" ],
"3" => [ "Subject" => "JavaScript" ]
];
$array3 = [];
foreach ( $array1 as $key1 => $value1 ) {
foreach ( $array2 as $key2 => $value2 ) {
if ( $key2 == $value1 ) {
$array3 [ $value1 ] = $array2 [ $value1 ];
}
}
}
print_r( $array3 );
?>
|
Output:
Array
(
[1] => Array
(
[Subject] => HTML
)
[2] => Array
(
[Subject] => CSS
)
[3] => Array
(
[Subject] => JavaScript
)
)
The above program will push the values from the array2 to array3 where the array3 is empty.
Program 3:
<?php
$department = [
"dept1" => "IT" ,
"dept2" => "CE" ,
"dept3" => "CS" ,
"dept4" => "EC"
];
$student = [
"IT" => [ "total_students" => "60" ],
"CE" => [ "total_students" => "65" ],
"CS" => [ "total_students" => "62" ]
];
foreach ( $department as $dept => $d ) {
foreach ( $student as $std => $s ) {
if ( $std == $d ) {
$student [ $d ][ "HOD" ] = "XYZ" ;
}
}
}
print_r( $student );
?>
|
Output:
Array
(
[IT] => Array
(
[total_students] => 60
[HOD] => XYZ
)
[CE] => Array
(
[total_students] => 65
[HOD] => XYZ
)
[CS] => Array
(
[total_students] => 62
[HOD] => XYZ
)
)
In the above program, there is no match for the dept4 in the student array so that it is not displayed in the output section.
Last Updated :
10 Oct, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...