Question

I made a simple function to check if array strings contain a certain name. However, since the names are getting more and more, I have to duplicate elseif all the time. If someone could help me to improve me function please? I'd like to check $arr names.

if the array looks like $arr = array('PDF', 'PSD', 'PNG', 'GIF', 'Mp3', 'JPG'....);

$i can be counted from mysql

 function checkname($arr, $name1, $name2, $name3......... ){
        if (strpos($arr, $name1) !== false) {
            return $name1;
        }elseif(strpos($arr, $name2) !== false){
            return $name2;

        ..............


        }else{
            return ' ';
        }
    }


checkname($arr[$i], 'PDF', 'PSD', 'PNG'........);
Was it helpful?

Solution

May I suggest array_slice() and func_get_args() to solve your argument problem?

<?php
    function checkname($arr, $name) {
        foreach (array_slice(func_get_args(), 1) as $name) {
            if (strpos($arr, $name) !== false) {
                return $name;
            }
        }

        return '';
    }
?>

..alternately, to solve it into infinity (or however many array values your memory can handle) why not pass an array, and simply do the following:

<?php
    function checkname($arr, $names) {
        foreach ($names as $name) {
            if (strpos($arr, $name) !== false) {
                return $name;
            }
        }

        return '';
    }

    checkname($arr[$i], array('PDF', 'PSD', 'PNG'));
?>

Note:

Your current code checks for the position of PDF, PSD, PNG etc., anywhere in your name (in uppercase!!), so MYPNG.PHP would go through fine, and doge.png would fail.

OTHER TIPS

Are you set on using a function with a dynamic number of parameters? I would pass two string arrays a parameters.

function checkname($arr, $names){
    foreach ($names as $value)
        if (in_array(strtoupper($value), $arr))
            return $value;
}

As mentioned in other comments, you will need to cleanse your input. It appears you database is storing your file types in upper case. Fell free to use strtoupper if this is true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top