Search code examples
phppseudocode

Check for currency sign


I found on the web a lots of complicated functions and options to see if the string starts with X this all where to complicated or to big how Can I do it in the fastest way for this Pseudocode

if price != startswith $ or €
    echo "<td>Free</td>"
else 
    echo "<td>"Price"</td>"

I only wanna check if there is a Dollar or Euro Sign as first char if not echo free else price


Solution

  • One option is using strripos() to check to see if the character is in position 0 of the string.

    $price = '$2.00';
    
    if(strripos($price, '$') === 0 || strripos($price, '€') === 0) {
        // do stuff 
    } else {
       // do other stuff
    }
    

    You can also use the strrpos() function in the same way.

    One of the reasons I use these two functions for something like this is to make sure that I am only dealing with one item in the string in the position I am looking for. If the last dollar sign's location is greater than 0 it means that I am not looking at a price string as I would expect it to be.