3

3 php constants i am not sure what they do

1. FILTER_REQUIRE_ARRAY

The name says it all I can agree no more but there is a function called
<em>filter_var/input_array()</em> which works in similar fashion; 
I've seen examples where recursive validation is required but 
not all element in the array are arrays some items are just scalar value 




FILTER_REQUIRE_SCALAR

    <?php 
        $x = 5;
        $y = [1, 2, 3];

        var_dump(filter_var($x,FILTER_REQUIRE_SCALAR));
        var_dump(filter_var($y,FILTER_REQUIRE_SCALAR));
    ?>

Consider The prev code that produces

bool(false)
bool(false)
as use can see $x is indeed Scalar


FILTER_FORCE_ARRAY

Always returns an array This is all the documentation i found about this in phpDoc give me an example about this please

1 Answer 1

6

FILTER_REQUIRE_ARRAY:

<?php

$arr = array(1,2,3,4,5);
$a = 3;
$result = filter_var( $arr,FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY);
var_dump($result); 

// output:
array (size=5)
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
  4 => int 5

$result = filter_var( $a,FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY);
var_dump($result); // boolean false

In this snippet, if one expects the input to be an array, by using the option FILTER_REQUIRE_ARRAY, it helps to avoid validating input containing a scalar value instead of an array.

filter_var_array() would not work in with the data in this example because it expects that the data is as follows:

An array with string keys containing the data to filter. (see Manual)

FILTER_REQUIRE_SCALAR:

<?php

$arr = array(1,2,3,4,5);
$a = 3;
$result = filter_var( $arr,FILTER_VALIDATE_INT, FILTER_REQUIRE_SCALAR);
var_dump($result); // boolean false

$result = filter_var( $a,FILTER_VALIDATE_INT, FILTER_REQUIRE_SCALAR);
var_dump($result); // int 3

In the preceding code, if one expects the input to be a scalar, by using the option FILTER_REQUIRE_SCALAR, it is useful in detecting if the input contains an array of info instead of the expected scalar value.

Here is a simple example that uses FILTER_FORCE_ARRAY:

<?php

$num = "1";
$result = filter_var( $num,FILTER_VALIDATE_INT,FILTER_FORCE_ARRAY);
var_dump($result);

// output:
array (size=1)
  0 => int 1

If the flag FILTER_FORCE_ARRAY were not present, then $result would be int 1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.