I am new to PHP and at the moment I am working on a PHP application. I have a string assigned to a PHP variable. It is actually a price value which is returned by a price function. So I get something like below:
$price_value = $100;
I need that $ currency symbol from above price value which is first character of total price_value string. Is there a way I could get first character of above price string so I should have something like below:
$currency_symbol = $
PHP has a ready made function to get position of any character in a PHP string which is
substr(). To get first character of overall string, you will need to do something like below:
<?php $price_value = '$100'; $currency_symbol = substr($price_value,0,1); echo $currency_symbol; ?>
Above code will return $ currency symbol in $currency_symbol variable. Please read more about substr() function.
You can also treat $price_value as an array and now you can get each character by its index position in the array. In your case you can get first character of string using PHP in the following way:
<?php $price_value = '$100'; $currency_symbol = $price_value; echo $currency_symbol; ?>
Remember each array index starts from 0, so to get 1 from $100, you will use $price_value.
Both of the above stated solutions will work perfectly usually, but in some cases when you are dealing with multibyte characters (UTF8), you will get � mark. So it is good practice to use mb_substr() function to get rid of such unwanted marks. In your case you can use mb_substr() function in the following way:
<?php $price_value = '$100'; $currency_symbol = mb_substr($price_value, 0, 1); echo $currency_symbol; ?>
Read more about mb_substr() function from PHP here.
You must be logged in to reply to this topic.