sweet potato
sweet potato

Reputation: 135

Combine certain values in one array with values in another array

I would like to combine the values which contain the prefix lt_ in $url with the values in $color and create a new array $new. Both arrays $url and $color store values for the next 36 hours:

print_r($url);

outputs

 Array(
     [0]  => "http://example.com/color/green.png",
     [1]  => "http://example.com/color/lt_green.png",
     [2]  => "http://example.com/color/lt_blue.png",
     [3]  => "http://example.com/color/blue.png",
     [4]  => "http://example.com/color/blue.png",
     [5]  => "http://example.com/color/yellow.png",
     ..
     [35] => "http://example.com/color/lt_blue.png",
     );

and

print_r($color);

outputs

Array(
     [0]  => "Green",
     [1]  => "Green",
     [2]  => "Blue",
     [3]  => "Blue",
     [4]  => "Blue",
     [5]  => "Yellow",
     ...
     [35] => "Blue",
     );

I have managed to find the string part lt_ in $url and get the keys in $new but how can I add "Light" (or lt_) to the corresponding values in $color to populate $new?

$new = array(
     [0]  => "Green",
     [1]  => "Light Green",
     [2]  => "Light Blue",
     [3]  => "Blue",
     [4]  => "Blue",
     [5]  => "Yellow",
     ...
     [35] => "Light Blue",
 );

I have managed to create an array with only the keys which values contain lt_:

$lt = 'lt_';
foreach($url as $key1=>$value1)
{
  foreach($color as $key2=>$value2)
  {
      if (strpos($value1,$lt) !== false)
      {
          $new[$key1] = array();
      }
  }
}

Upvotes: 1

Views: 55

Answers (1)

acontell
acontell

Reputation: 6932

If both arrays have the same size and the indexes correspond, you can iterate and add to the new array the color with the prefix or without it depending on the condition:

$arr = Array("http://example.com/color/green.png",
    "http://example.com/color/lt_green.png",
    "http://example.com/color/lt_blue.png",
    "http://example.com/color/blue.png",
    "http://example.com/color/blue.png",
    "http://example.com/color/yellow.png",);

$arr2 = Array(
    "Green",
    "Green",
    "Blue",
    "Blue",
    "Blue",
    "Yellow",);

$new = array();
for ($i = 0; $i < count($arr2); $i += 1) {
    (strpos($arr[$i], 'lt_') !== false) ?
                    $new[] = "Light " . $arr2[$i] :
                    $new[] = $arr2[$i];
}
print_r($new);

Upvotes: 1

Related Questions