Checking string > number into variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
benyboi
Forum Commoner
Posts: 80
Joined: Sat Feb 24, 2007 5:37 am

Checking string > number into variable

Post 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!
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Checking string > number into variable

Post 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;
There are 10 types of people in this world, those who understand binary and those who don't
benyboi
Forum Commoner
Posts: 80
Joined: Sat Feb 24, 2007 5:37 am

Re: Checking string > number into variable

Post 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
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Checking string > number into variable

Post by VladSun »

benyboi wrote:Can i just check, that "break;" in there, does that just stop looping when a match has been found?
Yes
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply