- rand
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Рандомные тексты да нет
- Php – Get random boolean true/false in PHP
- Best Solution
- Update
- Related Solutions
- Saved searches
- Use saved searches to filter your results more quickly
- License
- delight-im/PHP-Random
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
rand
При вызове без параметров min и max , возвращает псевдослучайное целое в диапазоне от 0 до getrandmax() . Например, если вам нужно случайное число между 5 и 15 (включительно), вызовите rand(5, 15) .
Функция не создаёт криптографически защищённые значения и не должна использоваться для криптографических целей или целей, требующих, чтобы возвращаемые значения были недоступны для разгадывания.
Если требуется криптографически безопасная случайная последовательность, Random\Randomizer может использоваться с движком Random\Engine\Secure . Для простых случаев использования функции random_int() и random_bytes() предоставляют удобный и безопасный API, поддерживаемый CSPRNG операционной системы.
Замечание: На некоторых платформах (таких как Windows) getrandmax() всего лишь 32767. Чтобы расширить диапазон, используйте параметры min и max , или обратитесь к функции mt_rand() .
Замечание: Начиная с PHP 7.1.0, rand() использует тот же алгоритм получения случайных чисел, что и mt_rand() . Для сохранения обратной совместимости, функция rand() позволяет задавать параметр max меньше, чем параметр min . Функция mt_rand() в такой ситуации будет возвращать false
Список параметров
Наименьшее значение, которое может быть возвращено (по умолчанию: 0)
Наибольшее значение, которое может быть возвращено (по умолчанию: getrandmax() )
Возвращаемые значения
Псевдослучайное значение в диапазоне от min (или 0) до max (или getrandmax() ).
Список изменений
Примеры
Пример #1 Пример использования rand()
Результатом выполнения данного примера будет что-то подобное:
Рандомные тексты да нет
Доброй ночи. Ув. Профессоры может у кого есть или помогите сделать маленький скрипт вопросов с ответом да или нет.
У каждого текста (вопроса) должен быть ответ да или нет.
Вывести на страницу текст (вопрос) который выберется рандомно из массива. И под ним две кнопочки да или нет.
По нажатию Да если ответ на вопрос Да вывести один текст если не правильный ответ т.е. НЕТ то другой.
Плюс ко всему текст на Да или Нет тоже должен быть рандомно выбранный из другого массива.
Ну в общем вот такую штуку нужно сделать.
На странице вот такой вопрос.
Верите ли вы, что Сороконожка и тарантул являются ядовитыми насекомыми?
Жмем Да
Выводится Текст (Молодец)
ниже — Еще раз задать вопрос?
Верите ли вы, что В России было два генералиссимуса: Суворов и Сталин?
Жмем Нет
Выводится Текст (Да ты прав)
Построить график, задать любые рандомные значения, чтобы проверить принадлежит точка области или нет
Здравствуйте, случилась проблема с лицензией Маткада 14. Нет возможности сейчас с ней разобраться.
Как сделать разные тексты разными цветами. Не несколько слов, а разные тексты разными цветами
Этот способ анимации идеально подходит для: </br> анимации трансформаций объекта, анимации.
Тексты
Дан текст; выяснить, является ли этот текст: десятичной записью целого числа. заранее спасибо!
тексты
Ребята, помогите с прогой. надо ппц ко вторнику сдать, а я проболела эту тему(((( Условие.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
ytf, Круто спасибо большое то что надо))))
Только вот вопрос можно ли вывод правильно или не правильно сделать на этой же странице на месте вопроса?
Ну т.е. может аяксом выводить на месте где вопрос только ответ?
Php – Get random boolean true/false in PHP
What would be the most elegant way to get a random boolean true/false in PHP?
But does casting an integer to boolean bring any disadvantages?
Or is this an «official» way to do this?
Best Solution
If you don’t wish to have a boolean cast (not that there’s anything wrong with that) you can easily make it a boolean like this:
Basically, if the random value is 1 , yield true , otherwise false . Of course, a value of 0 or 1 already acts as a boolean value; so this:
Is a perfectly valid condition and will work as expected.
Alternatively, you can use mt_rand() for the random number generation (it’s an improvement over rand() ). You could even go as far as openssl_random_pseudo_bytes() with this code:
$value = ord(openssl_random_pseudo_bytes(1)) >= 0x80;
Update
In PHP 7.0 you will be able to use random_int() , which generates cryptographically secure pseudo-random integers:
Related Solutions
Java – How to generate random integers within a specific range in Java
In Java 1.7 or later, the standard way to do this is as follows:
import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.
However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.
Before Java 1.7, the standard way to do this is as follows:
import java.util.Random; /** * Returns a pseudo-random number between min and max, inclusive. * The difference between min and max can be at most * Integer.MAX_VALUE - 1
. * * @param min Minimum value * @param max Maximum value. Must be greater than min. * @return Integer between min and max, inclusive. * @see java.util.Random#nextInt(int) */ public static int randInt(int min, int max) < // NOTE: This will (intentionally) not run as written so that folks // copy-pasting have to think about how to initialize their // Random instance. Initialization of the Random instance is outside // the main scope of the question, but some decent options are to have // a field that is initialized once and then re-used as needed or to // use ThreadLocalRandom (if using at least Java 1.7). // // In particular, do NOT do 'Random rand = new Random()' here or you // will get not very good / not very random results. Random rand; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; >
In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.
Javascript – Generate random string/characters in JavaScript
I think this will work for you:
function makeid(length) < var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) < result += characters.charAt(Math.floor(Math.random() * charactersLength)); >return result; > console.log(makeid(5));
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
The most convenient way to securely generate anything random in PHP
License
delight-im/PHP-Random
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
The most convenient way to securely generate anything random in PHP
$ composer require delight-im/random
require __DIR__ . '/vendor/autoload.php';
Generating integers and natural numbers
Random::intBetween(300, 999); // => e.g. int(510) // or Random::intBelow(5); // => e.g. int(1) // or Random::intValue(); // => e.g. int(935477113)
Generating floating-point numbers (floats, doubles or reals)
Random::floatBetween(1, 9); // => e.g. float(7.6388446512546) // or Random::floatBelow(499); // => e.g. float(281.51015805504) // or Random::floatValue(); // => e.g. float(0.05532844200834)
Generating boolean values
Random::boolValue(); // => e.g. bool(true)
Random::bytes(10); // => e.g. "\x58\x3b\x15\x94\x0a\x78\x52\xd0\x53\xb0"
Generating UUIDs (version 4)
Random::uuid4(); // => e.g. string(36) "892a24f9-c188-4d06-9885-cf5d8de4592b"
Generating hexadecimal strings
Random::hexLowercaseString(2); // => e.g. string(2) "5f" // or Random::hexUppercaseString(7); // => e.g. string(7) "B0F4B0C"
Generating strings consisting of letters
Random::alphaString(32); // => e.g. string(32) "GvogcpNdwaxsmOAzKGYwDwqfMOUkZvAn" // or Random::alphaHumanString(7); // => e.g. string(7) "KykrbXb" // or Random::alphaLowercaseString(2); // => e.g. string(2) "ce" // or Random::alphaLowercaseHumanString(32); // => e.g. string(32) "kqbgcmkttvmxjthwpgbhkgdfqhxqmmxh" // or Random::alphaUppercaseString(2); // => e.g. string(2) "IJ" // or Random::alphaUppercaseHumanString(7); // => e.g. string(7) "LJWLLHJ"
Generating strings consisting of letters and numbers
Random::alphanumericString(2); // => e.g. string(2) "h9" // or Random::alphanumericHumanString(7); // => e.g. string(7) "NF34gd4" // or Random::alphanumericLowercaseString(2); // => e.g. string(2) "4g" // or Random::alphanumericLowercaseHumanString(32); // => e.g. string(32) "wbdt3fdtg9c33dnxxtphp3qd9tgdvhbn" // or Random::alphanumericUppercaseString(2); // => e.g. string(2) "O7" // or Random::alphanumericUppercaseHumanString(32); // => e.g. string(32) "TWFHNNWLNKMPJMYKXHX3TXRCRFTFMYYW" // or Random::base32String(7); // => e.g. string(7) "AZUELC4" // or Random::base58String(32); // => e.g. string(32) "jut9s2LdWHT1EGJeBug3F58oYsaoU85s"
Generating strings consisting of letters, numbers and punctuation
Random::alphanumericAndPunctuationHumanString(32); // => e.g. string(32) "x%jJ7pWTFwc94ctX3phyy^KT~??H4+JY" // or Random::asciiPrintableString(32); // => e.g. string(32) "N~5_ kP5muxf,HeDY2(W_Bwy^qOkgOXa" // or Random::asciiPrintableHumanString(7); // => e.g. string(7) "_r=kb?v" // or Random::base64String(19); // => e.g. string(19) "I7A/H8D2R54uAo6jCQ3" // or Random::base64UrlString(4); // => e.g. string(4) "_6GS" // or Random::base85String(7); // => e.g. string(7) "j8o6sp:"
Generating strings from arbitrary characters sets or alphabets
Random::stringFromAlphabet('abcd+', 7); // => e.g. string(7) "ad+cabb"
Dividing output strings into segments
Using hyphens as dividers
\Delight\Random\Util::hyphenate('aaaaaaaaaa'); // => string(12) "aaaa-aaaa-aa" // or \Delight\Random\Util::hyphenate('bbbbbbbbbb', 3); // => string(13) "bbb-bbb-bbb-b"
\Delight\Random\Util::spaceOut('cccccccccc'); // => string(12) "cccc cccc cc" // or \Delight\Random\Util::spaceOut('dddddddddd', 3); // => string(13) "ddd ddd ddd d"
\Delight\Random\Util::segmentize('eeeeeeeeee', '/'); // => string(12) "eeee/eeee/ee" // or \Delight\Random\Util::segmentize('ffffffffff', '/', 3); // => string(13) "fff/fff/fff/f"
All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.
This project is licensed under the terms of the MIT License.
About
The most convenient way to securely generate anything random in PHP