Home  >  Article  >  Backend Development  >  How to convert array elements to hexadecimal in php

How to convert array elements to hexadecimal in php

青灯夜游
青灯夜游Original
2022-05-30 18:15:251955browse

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);".

How to convert array elements to hexadecimal in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$array=array("hello",524,"World");
var_dump($arr);
foreach($array as &$value){
	$value=bin2hex($value);
}
var_dump($arr);
?>

How to convert array elements to hexadecimal in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array("hello",524,"World");
var_dump($arr);
foreach($arr as &$v){
	$v=bin2hex($v);
}
unset($v); // 最后取消掉引用
var_dump($arr);
?>

How to convert array elements to hexadecimal in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn