Search code examples
phparraysfilteringcurrency

Remove elements in a flat array where the next element is not a price value


I have a large array of scraped names and prices similar to the following:

Array(
  [0] => apple3
  [1] => £0.40
  [2] => banana6
  [3] => £1.80
  [4] => lemon
  [5] => grape
  [6] => pear5
  [7] => melon4
  [8] => £2.32
  [9] => kiwi
  [10] => £0.50
)

I would like to remove the fruit names that are not immediately followed by a price. In the above example this would remove: [4] => lemon [5] => grape [6] => pear5 resulting in the following output:

Array(
  [0] => apple3
  [1] => £0.40
  [2] => banana6
  [3] => £1.80
  [7] => melon4
  [8] => £2.32
  [9] => kiwi
  [10] => £0.50
)

If the array needs to be converted to a string in order for me to do this that is not a problem, nor is adding values between the array items in order to aid with regex searches. I have so far been unable to find the correct regular expression to do this using preg_match() and preg_replace().

The most important factor is the need to maintain the sequential order of the fruits and prices in order for me at a later stage to convert this into an associative array of fruits and prices.


Solution

  • The following code does both of your tasks at once: getting rid of the fruit without value and turning the result into an associative array of fruits with prices.

    $arr = array('apple', '£0.40', 'banana', '£1.80', 'lemon', 'grape', 'pear', 'melon', '£2.32', 'kiwi', '£0.50' );
    
    preg_match_all( '/#?([^£][^#]+)#(£\d+\.\d{2})#?/', implode( '#', $arr ), $pairs );
    $final = array_combine( $pairs[1], $pairs[2] );
    
    print_r( $final );
    

    First, the array is converted to a string, separated by '#'. The regex captures all groups of fruits with prices - each stored as a separate subgroup in the result. Combining them into an associative array is a single function call.