<?xml version="1.0" encoding="utf-8" ?><rss version="2.0" xmlns:tt="http://teletype.in/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>@phpize</title><generator>teletype.in</generator><description><![CDATA[Most interesting code snippets from PHPize.online with comments]]></description><image><url>https://img3.teletype.in/files/e9/eb/e9ebaaed-a059-45a0-a3d8-e05f4553be52.png</url><title>@phpize</title><link>https://blog.phpize.online/</link></image><link>https://blog.phpize.online/?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><atom:link rel="self" type="application/rss+xml" href="https://teletype.in/rss/phpize?offset=0"></atom:link><atom:link rel="next" type="application/rss+xml" href="https://teletype.in/rss/phpize?offset=10"></atom:link><atom:link rel="search" type="application/opensearchdescription+xml" title="Teletype" href="https://teletype.in/opensearch.xml"></atom:link><pubDate>Sun, 12 Apr 2026 11:32:42 GMT</pubDate><lastBuildDate>Sun, 12 Apr 2026 11:32:42 GMT</lastBuildDate><item><guid isPermaLink="true">https://blog.phpize.online/MySQLi_fetch_column_function</guid><link>https://blog.phpize.online/MySQLi_fetch_column_function?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/MySQLi_fetch_column_function?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>PHP 8.1: MySQLi: fetch_column function</title><pubDate>Mon, 06 Feb 2023 18:14:39 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[Еще одно предложение внесенное Kamil Tekiela было включено в релиз РНР 8.1
Начиная с этого релиза еще один метод стал доступен в классе mysqli - метод fetch_column ранее имплементированный в библиотеке PDO]]></description><content:encoded><![CDATA[
  <p id="NRBp">Еще одно предложение <a href="https://wiki.php.net/rfc/mysqli_fetch_column" target="_blank">внесенное Kamil Tekiela </a>было включено в релиз РНР 8.1<br />Начиная с этого релиза еще один метод стал доступен в классе mysqli - метод fetch_column ранее имплементированный в библиотеке PDO</p>
  <p id="OF4n">Создадим маленькую тестовую таблицу</p>
  <pre id="uqMT" data-lang="sql">create table persons (
    id int primary key, 
    name varchar(64),
    age tinyint
);

insert into persons values (10, &#x27;Alice&#x27;, 18), (20, &#x27;Bob&#x27;, 22);

+====+=======+=====+
| id | name  | age |
+====+=======+=====+
| 10 | Alice | 18  |
| 20 | Bob   | 22  |
+----+-------+-----+</pre>
  <pre id="pJ6p" data-lang="php">$result = $mysqli-&gt;query(&quot;SELECT name FROM persons WHERE id = 10&quot;);

echo $result-&gt;fetch_column();
//Alice</pre>
  <p id="hbc7">В случае если запрос возвращает несколько колонок функция fetch_column  может вернуть значение из столбца номер которого передан в качестве параметра функции (нумерация колонок начинается с 0).</p>
  <pre id="aWxd" data-lang="php">$result = $mysqli-&gt;query(&quot;SELECT name, age FROM persons WHERE id = 10&quot;);

echo $result-&gt;fetch_column(1);
//18</pre>
  <p id="wPQg">Здесь можно <a href="https://phpize.online/sql/mysql57/e61e9314834351c0b4a33f0959cd439b/php/php81/cb90542f4d92ae0efcf08ec696a8e92f/" target="_blank">выполнить код PHP онлайн</a></p>
  <p id="tA99">Как и в случае с другими методами fetch_*, этот также перемещает внутренний указатель результата на следующую строку при вызове. Таким образом, вы не можете использовать fetch_column(i) для цикла с одним столбцом записи. Следующий пример демонстрирует эту ошибку:</p>
  <pre id="vRAq" data-lang="php">&lt;?php
$result = $mysqli-&gt;query(&quot;SELECT name, age FROM persons&quot;);

$name = $result-&gt;fetch_column(0);
$age  = $result-&gt;fetch_column(1);

// Returns Alice  name with Bob&#x27;s age
printf(&quot;Name: %s, age: %d&quot;, $name, $age);</pre>
  <p id="MUvA"><a href="https://phpize.online/sql/mysql57/b77bf62cd00f67bb433719a530ce2c8c/php/php81/d39ac72d052aa9f0009754256c9eec4a/" target="_blank">https://phpize.online/sql/mysql57/b77bf62cd00f67bb433719a530ce2c8c/php/php81/d39ac72d052aa9f0009754256c9eec4a/</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/mysql_execute_query</guid><link>https://blog.phpize.online/mysql_execute_query?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/mysql_execute_query?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>Новое в PHP 8.2: mysqli_execute_query / mysqli::execute_query</title><pubDate>Wed, 04 Jan 2023 21:17:57 GMT</pubDate><media:content medium="image" url="https://img2.teletype.in/files/d3/8f/d38fd08b-b3cb-47fe-9bc1-e88f4e78cc23.png"></media:content><category>PHP Tricks</category><description><![CDATA[В продолжение моей предидущей статьи хочу написать об ещё одном приятном нововведении в модуле mysqli
Начиная с версии PHP 8.2.0 появляется новая функция mysqli_execute_query или mysqli::execute_query если Вы предпочитаете объектно-ориентированный стиль.
Данная функция позволяет убить двух (трёх) зайцев сразу:
]]></description><content:encoded><![CDATA[
  <p id="8Zuy">В продолжение моей <a href="https://dev.to/rozhnev/php-81-mysqli-bind-in-execute-eeg" target="_blank">предидущей статьи</a> хочу написать об ещё одном приятном нововведении в модуле <code>mysqli</code><br />Начиная с версии PHP 8.2.0 появляется новая функция <code>mysqli_execute_query </code>или <code>mysqli::execute_query</code> если Вы предпочитаете объектно-ориентированный стиль.<br />Данная функция позволяет убить двух (трёх) зайцев сразу:<br /></p>
  <ul id="ypYW">
    <li id="l9rO">сгенерировать подготовленное выражение </li>
    <li id="He6y">выполнить его подставив значения из массива переменных</li>
    <li id="9RPU">получить результат в виде ассоциативного массива</li>
  </ul>
  <p id="LE8t">Давайте попробуем это на практике:</p>
  <pre id="7j62" data-lang="php">&lt;?php
$query = &#x27;SELECT Name FROM City WHERE District=? ORDER BY Name LIMIT 5&#x27;;

/* здесь происходит магия */
$result = $mysqli-&gt;execute_query($query, [&#x27;Nordrhein-Westfalen&#x27;]);
/* здесь происходит магия */

foreach ($result as $row) {
    printf(&quot;%s \n&quot;, $row[&quot;Name&quot;]);
}</pre>
  <p id="M1Py">Вы можете проверить этот код на <a href="https://phpize.online/s/LU" target="_blank">PHPize.online</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/how_to_get_all_variables_by_name</guid><link>https://blog.phpize.online/how_to_get_all_variables_by_name?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/how_to_get_all_variables_by_name?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>How to get all variables by name</title><pubDate>Wed, 23 Nov 2022 17:33:28 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[Assume we have in our code several variables named as $start1, $start2 .. $startN and we don't know how many such variables we have.]]></description><content:encoded><![CDATA[
  <p id="6DCR">Assume we have in our code several variables named as $start1, $start2 .. $startN and we don&#x27;t know how many such variables we have.</p>
  <p id="uPUE">How we can get (print values) of All such variables?</p>
  <p id="emNL">We can do this using <code><strong>get_defined_vars.</strong></code></p>
  <p id="Y1Mo">This function returns array of all defined variables, and after that we can filter this array only for variables that names starts with &quot;start&quot;:</p>
  <pre id="Vh5f" data-lang="php">&lt;?php

    $start1 = 10;
    $start2 = 20;
    $start3 = 30;
    $start4 = 40;
    $start5 = 50;
    
    //get all defined vars
    $vars = get_defined_vars();
    
    foreach($vars as $var=&gt;$val) {
        if (substr($var, 0, 5) == &#x27;start&#x27;) {
            printf(&#x27;$%s = %s &#x27;. PHP_EOL, $var, $val);
        }
    }
</pre>
  <p id="JRsr"><a href="https://phpize.online/sql/mysql57/undefined/php/php81/61035a896ff9ca31959a7635048654d3/" target="_blank">PHPize - online editor</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/sum_of_one_multidimensional_array_column</guid><link>https://blog.phpize.online/sum_of_one_multidimensional_array_column?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/sum_of_one_multidimensional_array_column?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>How to get sum of one multidimensional array column?</title><pubDate>Sun, 11 Sep 2022 20:52:29 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[php code online]]></description><content:encoded><![CDATA[
  <pre id="4Nua" data-lang="php">&lt;?php
$data = [
    [&#x27;id&#x27; =&gt; &#x27;3202&#x27;,&#x27;total&#x27; =&gt; &#x27;5&#x27;],
    [&#x27;id&#x27; =&gt; &#x27;3190&#x27;,&#x27;total&#x27; =&gt; &#x27;2&#x27;],
    [&#x27;id&#x27; =&gt; &#x27;3199&#x27;,&#x27;total&#x27; =&gt; &#x27;5&#x27;]
];

$total_column = array_column($data, &#x27;total&#x27;);

$sum = array_sum($total_column);

printf(&#x27;The sum of total column: %s&#x27;, $sum);
</pre>
  <p id="j0JQ"><a href="https://phpize.online/sql/mysql57/undefined/php/php8/01044d79182c9bffd2e9997908ac8759/" target="_blank">php code online</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/generate_random_string_in_PHP</guid><link>https://blog.phpize.online/generate_random_string_in_PHP?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/generate_random_string_in_PHP?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>How to generate random string in PHP?</title><pubDate>Sat, 10 Sep 2022 18:58:13 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[The simplest way is using bin2hex function:]]></description><content:encoded><![CDATA[
  <p id="9bpC">The simplest way is using bin2hex function:</p>
  <pre id="Qszy" data-lang="php">&lt;?php
$str_len = 8;
$random_string = bin2hex(random_bytes($str_len));

echo $random_string;
</pre>
  <p id="KDcq"><a href="https://phpize.online/sql/mysql57/undefined/php/php8/63425b66dc70c9881550b6fe1d71d5a6/" target="_blank">PHP online sandbox</a></p>
  <p id="qRKq">The another function is base64_encode.  Use it when you don&#x27;t care about special characters.</p>
  <pre id="eKsB" data-lang="php">&lt;?php

$str_len = 8;
echo base64_encode(random_bytes($str_len));</pre>
  <p id="p6HW"><a href="https://phpize.online/sql/mysql57/undefined/php/php8/4ab51a0d57fb9a6843fb8970417df203/" target="_blank">PHPize.online</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/effective_way_filter_multidimensional_array</guid><link>https://blog.phpize.online/effective_way_filter_multidimensional_array?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/effective_way_filter_multidimensional_array?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>What effective way to filter one multidimensional array by another?</title><pubDate>Fri, 02 Sep 2022 11:10:04 GMT</pubDate><description><![CDATA[Let we have 2 multidimensional arrays:]]></description><content:encoded><![CDATA[
  <p id="qGGy">Let we have 2 multidimensional arrays:</p>
  <pre id="a339" data-lang="php">$arr1 = [
    [&quot;URL&quot; =&gt; &quot;/1/1/1&quot;, &quot;cnt&quot; =&gt; &quot;1&quot;],
    [&quot;URL&quot; =&gt; &quot;/2/2/2&quot;, &quot;cnt&quot; =&gt; &quot;1&quot;],
    [&quot;URL&quot; =&gt; &quot;/3/3/3&quot;, &quot;cnt&quot; =&gt; &quot;1&quot;]
];

$arr2 = [
    [&quot;URL&quot; =&gt; &quot;/2/2/2&quot;, &quot;cnt&quot; =&gt; &quot;1&quot;],
    [&quot;URL&quot; =&gt; &quot;/4/4/4&quot;, &quot;cnt&quot; =&gt; &quot;1&quot;]
];</pre>
  <p id="df06">The problem is filer out all records from first array where exists records with same value of &quot;URL&quot; field</p>
  <p id="OEXK">Of course we can to use nested loops for this, but this is not best way</p>
  <p id="j1UV">The most effective solution is build map of all values of URL from second array and after use array_filter function:</p>
  <pre id="sKf6" data-lang="php">$url2arr = array_column($arr2, &#x27;url&#x27;, &#x27;url&#x27;);

$res = array_filter($arr1, fn($el)=&gt;!isset($url2arr[$el[&#x27;url&#x27;]]));

print_r($res);</pre>
  <p id="zthg"><a href="https://phpize.online/sql/mysql57/undefined/php/php81/be9ab8f0974d7f20bdb02415526c22e7/" target="_blank">php code online</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/round_number_to_second_digit</guid><link>https://blog.phpize.online/round_number_to_second_digit?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/round_number_to_second_digit?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>How round number up to second digit?</title><pubDate>Fri, 02 Sep 2022 10:51:50 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[The problem: below numbers should be rounded as described]]></description><content:encoded><![CDATA[
  <p id="Kk2W"><strong>The problem:</strong> below numbers should be rounded as described</p>
  <pre id="v6Nv">1256 »» 1300
1200,98 »» 1300
138 »» 140
11,01 »» 12</pre>
  <p id="s0Jn">For solve this problem we can use log10 function in next way:</p>
  <pre id="lWNg" data-lang="php">&lt;?php
function myRound($n) {
  $d = (int)log10($n) - 1;
  return ceil($n/10**$d) * 10**$d;
}</pre>
  <p id="7oTK"><a href="https://phpize.online/sql/mysql57/undefined/php/php81/ad7aa49c4b29a1d6b0f1b731d1ef8a3f" target="_blank">PHP code online</a></p>
  <p id="gkbt">Result of code execution:</p>
  <pre id="4uEz" data-lang="php">printf (&quot;%d &gt;&gt; %d&quot; . PHP_EOL, 1256, myRound(1256));
printf (&quot;%d &gt;&gt; %d&quot; . PHP_EOL, 1200.98, myRound(1200.98));
printf (&quot;%d &gt;&gt; %d&quot; . PHP_EOL, 138, myRound(138));
printf (&quot;%d &gt;&gt; %d&quot; . PHP_EOL, 11.001, myRound(11.001));</pre>
  <pre id="zook">1256 &gt;&gt; 1300
1200 &gt;&gt; 1300
138 &gt;&gt; 140
11 &gt;&gt; 12</pre>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/FFBw-rPtj42</guid><link>https://blog.phpize.online/FFBw-rPtj42?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/FFBw-rPtj42?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>Как в кириллице найти подмену на латинские символы?</title><pubDate>Thu, 01 Sep 2022 19:15:19 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[Вопрос:
Имеется текст на русском языке. Некоторые из символов заменены на латинские с идентичным написанием. (русская баква &quot;а&quot; на латинскую &quot;эй&quot; и т. д.) Требуется найти подмены в тексте.]]></description><content:encoded><![CDATA[
  <p id="0D0z"><strong>Вопрос:</strong><br />Имеется текст на русском языке. Некоторые из символов заменены на латинские с идентичным написанием. (русская баква &quot;а&quot; на латинскую &quot;эй&quot; и т. д.) Требуется найти подмены в тексте.</p>
  <p id="Wjzc"><strong>Дано:</strong><br /> Текст: &quot;Вакaнсия дня! Кpyпная тopгoвая cеть в связи с расширением объявляет набор coтpудникoв&quot;</p>
  <p id="p01E"><strong>Решение:</strong></p>
  <pre id="jVwJ" data-lang="php">  
&lt;?php

// присвоим значения переменным

$str = &quot;Вакaнсия дня! Кpyпная тopгoвая cеть в связи с расширением объявляет набор coтpудникoв&quot;;

// используем регулярные выражения для поиска латинских символов

$pattern = &quot;/\w/m&quot;;
echo preg_match_all($pattern, $str, $matches) ? &#x27;в тексте найдены подмены&#x27; : &#x27;чисто&#x27;;

// для наглядности заменим латинские символы на занки вопроса

echo preg_replace(&quot;/\w/m&quot;, &#x27;?&#x27;, $str);</pre>
  <p id="Oa5B">PHP editor online: <a href="https://phpize.online/sql/mysql57/null/php/php8/1150f69e356d833dbd01ff1607df52d9/" target="_blank">https://phpize.online/sql/mysql57/null/php/php8/1150f69e356d833dbd01ff1607df52d9/</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/use_str_pad_function_with_Unicode_string</guid><link>https://blog.phpize.online/use_str_pad_function_with_Unicode_string?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/use_str_pad_function_with_Unicode_string?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>How to use str_pad function with Unicode string?</title><pubDate>Thu, 01 Sep 2022 19:11:18 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[Data: Array of Unicode strings (football in different languages):]]></description><content:encoded><![CDATA[
  <p id="0Z77"><strong>Data:</strong> Array of Unicode strings (football in different languages):</p>
  <pre id="fMDk">  [
    &#x27;football&#x27;,
    &#x27;футбол&#x27;, // football in russian
    &#x27;ფეხბურთი&#x27;, // football in georgian
    &#x27;хөл бөмбөг&#x27;, // football in mongolian
    &#x27;bóng đá&#x27;  // football in vietnamese
  ]</pre>
  <p id="oLoK"><strong>The problem:</strong> Can not pad Unicode strings to same length using builtin function</p>
  <pre id="lf3j" data-lang="php">  
&lt;?php
// assign data to variables
$games = [
    &#x27;football&#x27;,
    &#x27;футбол&#x27;, // football in russian
    &#x27;ფეხბურთი&#x27;, // football in georgian
    &#x27;хөл бөмбөг&#x27;, // football in mongolian
    &#x27;bóng đá&#x27;  // football in vietnamese
];

// loop through $games array and print rows with built-in str_pad function
foreach ($games as $game) {
    echo str_pad($game, 20) . &#x27;|&#x27; . PHP_EOL;
}</pre>
  <p id="7laL"><strong>Wrong result:</strong> strings have different lengths after apply <em>str_pad()</em> function</p>
  <pre id="AM6G">  football            |
  футбол        |
  ფეხბურთი|
  хөл бөмбөг |
  bóng đá          |</pre>
  <pre id="R2k8" data-lang="php">  
&lt;?php
function mb_str_pad( $input, $pad_length, $pad_string = &#x27; &#x27;, $pad_type = STR_PAD_RIGHT) {
    $diff = strlen( $input ) - mb_strlen( $input );
    return str_pad( $input, $pad_length + $diff, $pad_string, $pad_type );
}

// loop through $games array and print rows with custom mb_str_pad function
foreach ($games as $game) {
    echo mb_str_pad($game, 20) . &#x27;|&#x27; . PHP_EOL;
}</pre>
  <p id="Mkvb"><strong>Result:</strong> the strings have same lengths after apply custom function <em>mb_str_pad()</em></p>
  <pre id="z24e">  football            |
  футбол              |
  ფეხბურთი           |
  хөл бөмбөг          |
  bóng đá             |</pre>
  <p id="SQDR"><a href="https://phpize.online/sql/mysql57/null/php/php8/f41cbbf648d8cc8647ddf45d806b898f/" target="_blank">PHP code online</a></p>

]]></content:encoded></item><item><guid isPermaLink="true">https://blog.phpize.online/find_the_closest_number_in_array</guid><link>https://blog.phpize.online/find_the_closest_number_in_array?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize</link><comments>https://blog.phpize.online/find_the_closest_number_in_array?utm_source=teletype&amp;utm_medium=feed_rss&amp;utm_campaign=phpize#comments</comments><dc:creator>phpize</dc:creator><title>How to find the closest number in an array?</title><pubDate>Thu, 01 Sep 2022 19:04:40 GMT</pubDate><category>PHP Tricks</category><description><![CDATA[Question: Given a number. What way to find the number closest to given in unsorted array?]]></description><content:encoded><![CDATA[
  <p id="y3QH"><strong>Question:</strong> Given a number. What way to find the number closest to given in unsorted array?</p>
  <p id="TEXQ"><strong>Data:</strong><br /> Unsorted numbers array: <strong>[5, 56, 23, 1, 89, 3]</strong><br /> Number: <strong>90</strong></p>
  <pre id="g2QE" data-lang="php">  
&lt;?php

// assign data to variables

$array  = [5, 56, 23, 1, 89, 3];
$number = 90;

// calculate distances between given number and each element of array

$distances = array_map(
  function($el) use ($number) {
    return abs($el - $number);
  },
  $array 
);

//get monimal distance position

$index = array_keys($distances, min($distances))[0];

// print out closest number

echo &quot;Closest number is: &quot; . $array[$index];</pre>
  <p id="W85v"></p>
  <p id="1Tf1"><a href="https://phpize.online/sql/mysql57/null/php/php8/c9c3c872213c19b5d0a368ce911bcd38/" target="_blank">PHP code online</a></p>

]]></content:encoded></item></channel></rss>