1

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
1
  • assign the same keys to $values. Commented Jan 15, 2016 at 8:10

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is solution with array_map:

array_map(function($key, $f, $v){
    echo "Items are ". $key. " ". $v." " . $f ."<br>";
}, array_keys($fields), $fields, $values);

1 Comment

@OumAlaa, you're welcome. Yes, array_map and array_walk are pretty convenient functions for iterating through array(s)

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.