Home > Article > Backend Development > How to convert array elements to hexadecimal in php
Conversion method: 1. Use the foreach statement to traverse the array by referencing the loop, with the syntax "foreach ($array as &$v){//loop body}"; 2. In the loop body, use The bin2hex() function converts array elements to hexadecimal, the syntax is "$v=bin2hex($v);".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php will Method of converting to hexadecimal
In PHP, you can use the foreach statement to traverse the array, and use bin2hex() in the loop to convert the array elements to hexadecimal.
1. Use the foreach statement to traverse the array through a reference loop.
foreach ($array as &$value){ //循环体语句块; }
Add & before $value, so that the foreach statement will assign the value by reference instead of copying. A value, then operating on the array within the loop body will affect the array itself.
2. In the loop body, use bin2hex() to convert the array element $value into hexadecimal
bin2hex() function converts the string of ASCII characters is a hexadecimal value.
Implementation code:
<?php header('content-type:text/html;charset=utf-8'); $array=array("hello",524,"World"); var_dump($arr); foreach($array as &$value){ $value=bin2hex($value); } var_dump($arr); ?>
Instructions: In the output of the above example, it can be seen that before the last element , there is an &, that's because the $value reference of the last element of the array will remain after the foreach loop. We need to use unset() to destroy it.
<?php header('content-type:text/html;charset=utf-8'); $arr=array("hello",524,"World"); var_dump($arr); foreach($arr as &$v){ $v=bin2hex($v); } unset($v); // 最后取消掉引用 var_dump($arr); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert array elements to hexadecimal in php. For more information, please follow other related articles on the PHP Chinese website!