Page 1 of 1

Checking string > number into variable

Posted: Sat Jan 10, 2009 2:56 pm
by benyboi
Hello,

I am looking for a way to optimize my script, i really think there will be a better way to do it but i cant think how...

Basically, i have a script that assigns a variable depending on a file name, like so:

Code: Select all

 
$file = substr($files_value, 0, 5);
if ($file == "90210") {
    $fpid = 994;
}
 
$file = substr($files_value, 0, 16);
if ($file == "Filename.Version") {
    $fpid = 992;
}
 
$file = substr($files_value, 0, 9);
if ($file == "Something") {
    $fpid = 956;
}
 
As you can this method works but its getting messy/unprofessional now that i have more than 100 checks like this.

Is there someway else i can do this? I know that if the file names were of the same length you could use a simple array $fpid = $array['$file'] but thats where the problem is - different lengths of filenames means the actual string length changes each time.

It would be nice to use an array, such as $files = array("90210", "Filename.Version", "Something", ...) but i dont see how i can easily do this with different length filenames.

Anyone able to offer some sugestions?

Thanks!

Re: Checking string > number into variable

Posted: Sat Jan 10, 2009 3:02 pm
by VladSun
You can use something like this:

Code: Select all

 
$search = 'file2';
$result = 0;
 
$file_pid_mapping = array(
924 => 'file1',
945 => 'file2',
....
);
 
foreach($file_pid_mapping as $pid=>$file)
    if (strpos($file, $search) === 0)
    {
         $result = $pid;
         break;
    }
 
echo $result;

Re: Checking string > number into variable

Posted: Sat Jan 10, 2009 3:10 pm
by benyboi
Thank you! That's perfect!!

Can i just check, that "break;" in there, does that just stop looping when a match has been found?

Thanks so much :D

Re: Checking string > number into variable

Posted: Sat Jan 10, 2009 3:16 pm
by VladSun
benyboi wrote:Can i just check, that "break;" in there, does that just stop looping when a match has been found?
Yes