Skip to content
Advertisement

Merge an array value with another array

I Have 2 arrays:

$fields = array('field1'=>'INT', 'field2'=>'STR', 'field3'=>'INT');
$values = array('pour field1', 'pour field2', 'pour field3');

I am looking to merge both of them to get the below result using foreach:

foreach($fields as $setK=>$setV){
            
    echo 'k '.$setK.' v '.$setV.'<br />';
            
    echo "Items are $setK 'THE VALUES OF VALUES ARRAY HERE' $setV";
            
}

So the result will be displayed like:

Items are field1 pour field1 INT
Items are field2 pour field2 STR
Items are field3 pour field3 INT

Advertisement

Answer

foreach (array_keys($fields) as $i => $key) {
    echo 'Items are ', $key, ' ', $values[$i], ' ', $fields[$key];
}

You need to keep a running integer count of the key offset to be able to get the same index from $values; we’re doing this here by looping over the keys and using their index as $i.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement