简体   繁体   中英

How do i print separate digits from a 3 digit php variable?

Like I am attempting to use data by using SQL query. After that, the PHP variable contain 123 . Now I want to print 1, 2 and 3 separately on html page.

A string is basically an array of characters, so you can access each char by position easily. You will need to make sure that your value is a string - if it is a number you need to cast it .

<?php
$value = 123;

// Cast our value to a string
$stringValue = (string) $value;

$firstChar = $stringValue[0];
$secondChar = $stringValue[1];
$thirdChar = $stringValue[2];
echo $firstChar.PHP_EOL;
echo $secondChar.PHP_EOL;
echo $thirdChar.PHP_EOL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM