WTF is that!? - PHP will drive me crazy; Drupal FAPI too!

Share and options

What do you think this code will output:

<?php
  $foo
= '7rray';
  echo (int)
$foo;
?>

If you answered NULL, 0 or '7rray', you're absolutely wrong. The magic with PHP is whatever you use (int) or intval() you get absolutely weird results, because it'll try to parse your string as an integer whatever is in it.

So, let's try and play a bit in console mode:

pounard@guinevere:~$ php -a
Interactive shell

php > $foo = "7rray";
php > echo (int) $foo;
7
php > echo (float) $foo;
7
php > echo $foo;
7rray
php > echo ! is_numeric($foo);
1
php >

WTF!!!!

Ok, reading the doc makes some things clear, PHP will try to get an int from anything you give him to, as long as you use a cast.

Look at this element validation function (Drupal FAPI):

<?php
function assistant_slider_validate($element, &$form_state) {
  if (
$value = $element['slider_value']['#value']) {
   
// Check for value integrity
   
if (! is_numeric($value) || $value < 0 || $value > 100) {
     
$error_field = implode('][', $element['#parents']).']';
     
form_set_error($error_field, t('Illegal value for slider detected: @value', array('@value' => $value)));
     
form_set_value($element, NULL, $form_state);
    }
    else {
     
// What's really magic with Drupal, is they use form values as array keys
      // when they are parsing a #tree'ed form. So, be careful with float
      // values, you need to cast is as string.
     
form_set_value($element, (string) $value, $form_state);
    }
  }
  else {
   
form_set_value($element, NULL, $form_state);
  }
}
?>

Why do the fuck I finally get "7rray" instead of the nice "70" value my slider submit?

EDIT: I think the guilt goes to ahah_helper module. I'm not sure, but when submitting my form through AJAX to use my nice preview feature I was coding, I have the "7rray" problem, but when I submit it without AJAX, I don't get these errors.
I think it's due to the validation process skip during AJAX submission.

Update on Febuary the 3rd: It seems that intval() PHP function does the C atoi() stdlib vulgaris function, and reproduce exactly the same behavior. This sounds quite right after some thinking. But the fact the (int) cast does the same thing is much more annoying, I always prefer cast because I want to ensure I get an int, and if invalid, I want him to NULL or 0. The fact here is I should use the is_numeric() method. But because ahah_helper skipped the validation process on partial form submission, my custom element validator that does it is never ran.