0

How can I check if the first 2 characters of an array are 0x? here is an example:

$hex = "0xFFFF";
if($hex[0:2].find('0x')==0)
{
print("0x Found.");
}
else
{
print("0x Not Found.");
}

Can anyone create an alternative that works?

5
  • How about switch statements Commented Dec 28, 2012 at 23:47
  • Are you really talking about an array? $hex in your example is a string. Commented Dec 28, 2012 at 23:49
  • The first two characters of an array or string? In PHP these are different things (thought they do have the concept of array access for strings) Commented Dec 28, 2012 at 23:49
  • $hex[0:2] - PHP does not have nice stuff like that. Consider using Python if you like having a nice operator to get a slice from a string. Commented Dec 28, 2012 at 23:50
  • I was just using a string as an example but the solution is pretty much the same for an array. Commented Dec 28, 2012 at 23:54

4 Answers 4

1

If $hex is a string this is rather easy

if (strpos($hex, '0x') === 0) {
    print("0x Found.");
} else {
    print("0x Not Found.");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Using strnicmp (manual) looks good.

$hex = '0xFFFF';
if (strnicmp($hex, '0x', 2) == 0)
{
    print("0x Found.");
}
else
{
    print("0x Not Found.");
}

Looks for an insensitive '0x' string at the beginning of your $hex var.

Comments

1
$hex = '0xFFFF';
if ($hex[0].$hex[1] == '0x')
{
    print("0x Found.");
}
else
{
    print("0x Not Found.");
}

Without needing to use any function. See this page for it's usage.

Comments

0

You can access string characters as an array to get the first and second index and check if they are 0 and x.

<?php
$hex = array("0xFFF","5xFFF","0xDDD");
$len = count($hex);
$msg = "";
for ($i = 0; $i < $len; $i++) {
    if ($hex[$i][0] == "0" && $hex[$i][1] == "x") {
        $msg .= $hex[$i] . ' starts with 0x!' . "\n";
    }
}
echo ($msg);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.