Ask Your Question

How can arrays be combined based on the endings of their keys in PHP?

asked 2022-03-21 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-09-02 18:00:00 +0000

scrum gravatar image

In PHP, arrays can be combined based on the endings of their keys using the following steps:

  1. First, define two arrays to be combined.

  2. Loop through the first array using a foreach loop.

  3. Check each key of the first array to see if it ends with a certain suffix. This can be done using the substr() function to extract the last few characters of the string.

  4. If the suffix matches, add the value of the key in the first array to the corresponding key in the second array.

  5. If the suffix does not match, add the key and value to the second array as a new entry.

  6. After looping through the first array, the second array will contain all the combined values.

Here's an example code snippet:

$array1 = array(
   "apple_1" => "red",
   "banana_2" => "yellow",
   "orange_1" => "orange"

$array2 = array(
   "apple_2" => "green",
   "banana_1" => "green",
   "orange_2" => "orange"

foreach($array1 as $key => $value){
   $suffix = substr($key, -2); //get last two characters of key
   if($suffix == "_1"){
      //add value to corresponding key in array2
      $new_key = str_replace("_1", "_2", $key); //replace suffix with "_2"
      $array2[$new_key] = $value;
   } else {
      //add key and value as new entry in array2
      $array2[$key] = $value;



    [apple_2] => red
    [banana_1] => green
    [orange_2] => orange
    [banana_2] => yellow

In this example, the two arrays are combined by replacing the "1" suffix in the keys of the first array with "2" and adding their corresponding values to the second array. If the key in the first array does not end with "_1", it is simply added as a new entry in the second array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2022-03-21 11:00:00 +0000

Seen: 8 times

Last updated: Sep 02 '21