3

I have an array with filenames.

I want to check if the array have a file with extension '.txt'.

How can I do that?

in_array only checks for a specific value.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
trogne
  • 3,402
  • 3
  • 33
  • 50

7 Answers7

4

Try array_filter. In the callback, check for the presence of the .txt extension.

If the result of array_filter has entries (is truthy), then you can get the first one or all of them. If the array is empty, there were no matches.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

You can loop through the items in your array, and then perform either a regular expression or a strpos match on each item. Once you find a match, you can return true.

With strpos():

$array = array('one.php', 'two.txt');

$match = false;
foreach ($array as $filename) {
    if (strpos($filename, '.txt') !== FALSE) {
        $match = true;
        break;
    }
}

With regex:

$array = array('one.php', 'two.txt');

$match = false;
foreach ($array as $filename) {
    if (preg_match('/\.txt$/', $filename)) {
        $match = true;
        break;
    }
}

Both will result in $match equating to true.

Maccath
  • 3,936
  • 4
  • 28
  • 42
1
$files = array('foo.txt', 'bar.txt', 'nope.php', ...);

$txtFiles = array_filter($files, function ($item) {
    return '.txt' === substr($item, -4); // assuming that your string ends with '.txt' otherwise you need something like strpos or preg_match
});

var_dump($txtFiles); // >> Array ( [0] => 'foo.txt', [1] => 'bar.txt' )

The array_filter function loops through the array and passes the value into a callback. If the callback returns true, it will keep the value, otherwise it will remove the value from the array. After all items are passed in the callback, the result array is returned.


Oh, you just want to know if .txt is in the array. Some other suggestions:

$match = false;

array_map(function ($item) use ($match) {
    if ('.txt' === substr($match, -4)) {
        $match = true;
    }
}, $filesArray);
$match = false;
if (false === strpos(implode(' ', $filesArray), '.txt')) {
    $match = true;
}
Wouter J
  • 41,455
  • 15
  • 107
  • 112
  • @danronmoon thank you, I just edited it. (at first I thought I will solve the problem with `array_map` which has the `callback, input` order...) – Wouter J Dec 19 '12 at 16:24
0
$iHaz = FALSE;

foreach ($arr as $item) {
    if (preg_match('/\.txt$/', $item)) {
        $iHaz = TRUE;
        break;
    }
}

Contrarily to other answers suggesting array_filter, I don't return something. I just check if it exists in the array. Besides, this implementation is more efficient than array_filter because it breaks out of the loop once it's found something.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
0

Since you are dealing with files you should use array_filter and pathinfo

$files = array_filter(array("a.php","b.txt","z.ftxt"), function ($item) {
    return pathinfo($item, PATHINFO_EXTENSION) === "txt";
});

var_dump($files); // b.txt
Baba
  • 94,024
  • 28
  • 166
  • 217
0

Filter your array results based on the file extension using array_filter:

// Our array to be filtered
$files = array("puppies.txt", "kittens.pdf", "turtles.txt");

// array_filter takes an array, and a callable function
$result = array_filter($files, function ($value) {
    // Function is called once per array value
    // Return true to keep item, false to filter out of results
    return preg_match("/\.txt$/", $value);
});

// Output filtered values
var_dump($result);

Which results in the following:

array(2) {
  [0]=> string(11) "puppies.txt"
  [2]=> string(11) "turtles.txt"
}

Execute it: http://goo.gl/F3oJr

Sampson
  • 265,109
  • 74
  • 539
  • 565
0

If you want a filtered array containing only strings ending in .txt, then PHP8 has a native function for you.

Code: (Demo)

$array = ['one.php', 'two.txt'];

var_export(
    array_filter(
        $array,
        fn($v) => str_ends_with($v, '.txt')
    )
);

If you want a true/false result and don't need to iterate the whole array, then conditionally break the loop. (Demo)

$found = false;
foreach ($array as $filename) {
    if (str_ends_with($filename, '.txt')) {
        $found = true;
        break;
    }
}
var_export($found);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136