Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to unique numeric value in php

Tags:

php

I needed a unique internal int to use that would represent several random content types that I couldn't hard code as class constants or config options. Yet I didn't want to refer to "2" when I could use the easier to follow term "post". So though up the a way to get a INT value from a string which seems to work fairly collision free for a couple items.

Is there a way to do this in php rather than what I built?

$strings = array('post', 'comment', 'blog', 'article', 'forum', 'news', 'page');

foreach( $strings as $string ) {

    print $string . ' = ';

    $string = str_split($string);
    $sum = 0;
    foreach( $string as $char ) {
        $sum += ord($char);
    }

    var_dump( $sum );

    print '<br />';
}

This has nothing to do with user input so don't worry about the obvious flaws in the design.

:EDIT:

I need a numeric index for storing in a database for fast look ups. i.e. to tell "posts" from "articles" or "news". Yet I don't know what those 1-8 types of content will be called so I can't hard code those as constants in the app. Therefore, the best thing I could figure would be to create a numeric version of each word (which means checking to make sure two words don't sum up to the same number).

If this were for a system that would have more than 8 words then this method is doomed to failure do to the high probability of sum collisions. Also, if I had a choice in knowing what words would be used then this would also be terrible design as class constants would work much better.

like image 662
Xeoncross Avatar asked Dec 07 '22 06:12

Xeoncross


1 Answers

You could use crc32, which is a checksumming function that simply returns a 4 byte integer.

like image 140
ryeguy Avatar answered Feb 17 '23 23:02

ryeguy