skip to Main Content

I have a txt file which has rows like below.

apple, green, fruit
banana, yellow, fruit
carrot, orange, vegetable

I am trying to get the item, by the color.
So if I have green I want to return apple, if I have yellow I want to return banana.

I do

$array = file($file_path);

Which outputs

Array ( [0] => apple, green, fruit
        [1] => banana, yellow, fruit
        [2] => carrot, orange, vegetable
    )

I now want to do something like below, find $input in the position 1 and return position 0 for that row.

$input = 'green';
$result = array_search($input, array_column($array, '1', '0')); // return apple.

But the $result returns empty. Do I need to convert the CSV to an array, or is there another way?
Thanks

2

Answers


  1. If you want to read your csv file; you can start with that and twik as you need
    (this is just an example for small files not recommended for large ones)

    if (($open = fopen($file_path, "r")) !== false) {
        while (($data = fgetcsv($open, 1000, ",")) !== false) {
            $array[] = $data;
        }
     
        fclose($open);
    }
     
    // Display you array data, so you can make the right search
    
    var_dump($array);
    
    
    Login or Signup to reply.
  2. Each value in $array is a string, like "apple, green, fruit", and not an array like [ apple, green, fruit ]. So you first have to loop over the array and turn each $value into an array to make your code work:

    $array = [
      'apple, green, fruit',
      'banana, yellow, fruit',
      'carrot, orange, vegetable'
    ];
    
    $input = 'green';
    
    $arrayWithSubarrays = array_map(fn($value) => explode(', ', $value), $array);
    
    $result = array_search($input, array_column($arrayWithSubarrays, 1, 0));
    
    print_r($result);   // Output: apple
    

    Alternative approaches:

    If the input array contains a lot of entries you might want to leave the loop early. In that case array_map is an overkill as it will always loop over all array entries:

    $array = [
      'apple, green, fruit',
      'banana, yellow, fruit',
      'carrot, orange, vegetable'
    ];
    
    $input = 'green';
    
    $result = null;
    
    foreach ($array as $value) {
      if (str_contains($value, ", $input, ")) {
        $result = strtok($value, ',');   // or: explode(',', value)[0]
        break;
      }
    }
    
    print_r($result);   // Output: apple
    

    Another possibility is to filter the entries. The result will be an array (think of a case where more than one fruit is having the same color):

    $input = 'green';
    
    $result = array_filter($array, fn($value) => str_contains($value, ", $input, "));
    
    print_r($result);
    
    // Output:
    
    Array
    (
        [0] => apple, green, fruit
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search