Convert string to unique numeric value in php

I needed a unique internal int to use, which would represent several random types of content that I could not hard code as class constants or configuration parameters. However, I did not want to refer to "2" when I could use the lighter sequence of the term "post". So, despite the way to get the INT value from a string that seems to work quite freely for a couple of elements.

Is there a way to do this in php and not in 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 obvious design flaws.

: EDIT:

. "" "" "". , , 1-8 , . ( , ).

, 8 , , . , , , , , .

+3
6

crc32, , 4 .

+9

, . 3 + 3 = 6; 2 + 2 + 2 = 6;

. , .

..: md5(), sha1(), sha256() ..

PHP5 spl_object_hash(), . http://us3.php.net/manual/en/function.spl-object-hash.php

ps: , . , , .

+1

, " ", C, ++, #, Pascal, Java .. , , MySQL , ENUM .

+1
$strings = array('post' => 0, 'comment' => 1, 'blog' => 2, 'article' => 3, 'forum' => 4, 'news' => 5, 'page' => 6);

$s = 'comment';
$s_as_int = $strings[$s];
0
<?php
$strings = array('post', 'comment', 'blog', 'article', 'forum', 'news', 'page');

foreach( $strings as $string )
{
    echo $string . ' = ' . base_convert(md5($string), 16, 10) . '<br />';
}
?>
0

array_flip() array_search() ?

, dictionary, (MySQL)

CREATE TABLE `dictionary` (
  `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `word` VARCHAR(25),
  UNIQUE `word` (`word`)
)
0

Source: https://habr.com/ru/post/1717105/


All Articles