Php find string type

PHP: Check if variable is type of string AND is not empty string?

I need to check if the passed variable is type of string, and it is not empty. I have the following function:

function isNonEmptyStr($var) < if(isset($var)) < if(is_string($var)) < if(strlen($var) >0) < return true; >> > return false; > 
echo(isNonEmptyStr(''));// false echo(isNonEmptyStr(' '));// true echo(isNonEmptyStr('a'));// true echo(isNonEmptyStr('1'));// true echo(isNonEmptyStr(1));// false echo(isNonEmptyStr(0));// false echo(isNonEmptyStr(0.0));// false echo(isNonEmptyStr(0.1));// false echo(isNonEmptyStr(array()));// false echo(isNonEmptyStr(new myObj()));// false echo(isNonEmptyStr(true));// false echo(isNonEmptyStr(false));// false echo(isNonEmptyStr(null));// false 

The function works fine. My question: Is there a way to improve function performance without effecting the results? I’m talking about «micro optimization» (I use this function very heavily). EDIT: For those who are asking:

echo(isNonEmptyStr(0));// should return false, because it's not a string echo(isNonEmptyStr(1));// should return false, because it's not a string echo(isNonEmptyStr('0'));// should return true, because it's a non-empty string echo(isNonEmptyStr('1'));// should return true, because it's a non-empty string 

Note: a non-empty string = a string which if tested with strlen() function it would return > 0

5 Answers 5

Here is a simple little benchmarking script you can modify to see what works best. I just tried a few variations of the same thing, the first one is the fastest by a small margin, but they are basically all the same. And there isn’t really a simpler way for you to write it.

Читайте также:  Full stack python flask

Also $val === » is slightly faster than empty($val) , on top of being more strictly correct for you.

Additionally, since this is basically a one liner, why not just cut the overhead of making it a function and call is_string($val) && $val !== » directly. It don’t make a huge difference, but its noticeable for millions of iterations, but I doubt this procedure will be the main bottleneck in any of your code ever.

function is_non_empty_string_1($val) < return is_string($val) && $val !== ''; >function is_non_empty_string_2($val) < return gettype($val) === 'string' && $val !== ''; >function is_non_empty_string_3($val) < switch (true) < case !is_string($val): return false; case $val === '': return false; >return true; > $values = array('', '1', new stdClass(), 1, 2, 3, 999, array(), array()); $runs = 2000000; function benchmark($test, $values, $runs, $func) < $time = time(); for ($i = 0; $i < $runs; $i++) < foreach ($values as $v) < $func($v); >> echo $test . '. ' . (time() - $time) . PHP_EOL; > benchmark(1, $values, $runs, 'is_non_empty_string_1'); benchmark(2, $values, $runs, 'is_non_empty_string_2'); benchmark(3, $values, $runs, 'is_non_empty_string_3'); 

Источник

is_string

Finds whether the type of the given variable is string.

Parameters

The variable being evaluated.

Return Values

Returns true if value is of type string , false otherwise.

Examples

Example #1 is_string() example

$values = array( false , true , null , ‘abc’ , ’23’ , 23 , ‘23.5’ , 23.5 , » , ‘ ‘ , ‘0’ , 0 );
foreach ( $values as $value ) echo «is_string(» ;
var_export ( $value );
echo «) color: #007700″>;
echo var_dump ( is_string ( $value ));
>
?>

The above example will output:

is_string(false) = bool(false) is_string(true) = bool(false) is_string(NULL) = bool(false) is_string('abc') = bool(true) is_string('23') = bool(true) is_string(23) = bool(false) is_string('23.5') = bool(true) is_string(23.5) = bool(false) is_string('') = bool(true) is_string(' ') = bool(true) is_string('0') = bool(true) is_string(0) = bool(false)

See Also

  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_bool() — Finds out whether a variable is a boolean
  • is_object() — Finds whether a variable is an object
  • is_array() — Finds whether a variable is an array

User Contributed Notes 3 notes

Using is_string() on an object will always return false (even with __toString()).

class B public function __toString () return «Instances of B() can be treated as a strings!\n» ;
>
>

$b = new B ();
print( $b ); //Instances of B() can be treated as a strings!
print( is_string ( $b ) ? ‘true’ : ‘false’ ); //false
?>

As noted earlier, is_string() returns false on an object that has a __toString() method. Here is a simple way to do a check that will work:

// determine if the passed argument can be treated like a string.
function is_stringy ( $text ) return ( is_string ( $text ) || ( is_object ( $text ) && method_exists ( $text , ‘__toString’ ));
>

is_string() of an integer or float returns false, so it might be useful to include an is_numeric() when checking if a value is stringy:

function is_stringy ( $val ) return ( is_string ( $val ) || is_numeric ( $val )
|| ( is_object ( $val ) && method_exists ( $val , ‘__toString’ )));
>
?>

Test code (which should print «vector N OK» for each test vector):
foreach ([[ NULL , false ], [ false , false ], [ true , false ],
[ 0 , true ], [[], false ], [ 0.1 , true ], [ «x» , true ],
[ «» , true ], [new Exception ( «x» ), true ]] as $idx => $vector ) list ( $val , $expected ) = $vector ;
if ( is_stringy ( $val ) != $expected ) print ( «mismatch at $idx \n» );
var_dump ( $val );
> else print ( «vector $idx OK\n» );
>
>
?>

Источник

gettype

Returns the type of the PHP variable value . For type checking, use is_* functions.

Parameters

The variable being type checked.

Return Values

  • «boolean»
  • «integer»
  • «double» (for historical reasons «double» is returned in case of a float , and not simply «float» )
  • «string»
  • «array»
  • «object»
  • «resource»
  • «resource (closed)» as of PHP 7.2.0
  • «NULL»
  • «unknown type»

Changelog

Version Description
7.2.0 Closed resources are now reported as ‘resource (closed)’ . Previously the returned value for closed resources were ‘unknown type’ .

Examples

Example #1 gettype() example

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

The above example will output something similar to:

integer double NULL object string

See Also

  • get_debug_type() — Gets the type name of a variable in a way that is suitable for debugging
  • settype() — Set the type of a variable
  • get_class() — Returns the name of the class of an object
  • is_array() — Finds whether a variable is an array
  • is_bool() — Finds out whether a variable is a boolean
  • is_callable() — Verify that a value can be called as a function from the current scope.
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_null() — Finds whether a variable is null
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_object() — Finds whether a variable is an object
  • is_resource() — Finds whether a variable is a resource
  • is_scalar() — Finds whether a variable is a scalar
  • is_string() — Find whether the type of a variable is string
  • function_exists() — Return true if the given function has been defined
  • method_exists() — Checks if the class method exists

User Contributed Notes 2 notes

Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.

string — string // OK
int — integer // Type mismatch
bool — boolean // Type mismatch
array — array // OK

Same as for «boolean» below, happens with integers. gettype() return «integer» yet proper type hint is «int».

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.

Источник

How to get the real type of a value inside string?

I was searching here on StackOverflow about converting string to the real value and i didn’t found. I need a function like «gettype» that does something like the result above, but i can’t do it all :s

gettypefromstring("1.234"); //returns (doble)1,234; gettypefromstring("1234"); //returns (int)1234; gettypefromstring("a"); //returns (char)a; gettypefromstring("true"); //returns (bool)true; gettypefromstring("khtdf"); //returns (string)"khtdf"; 

3 Answers 3

Here is the function if someone want it:

function gettype_fromstring($string) < // (c) José Moreira - Microdual (www.microdual.com) return gettype(getcorrectvariable($string)); >function getcorrectvariable($string)< // (c) José Moreira - Microdual (www.microdual.com) // With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack) /* FUNCTION FLOW */ // *1. Remove unused spaces // *2. Check if it is empty, if yes, return blank string // *3. Check if it is numeric // *4. If numeric, this may be a integer or double, must compare this values. // *5. If string, try parse to bool. // *6. If not, this is string. $string=trim($string); if(empty($string)) return ""; if(!preg_match("/[^0-9.]+/",$string))< if(preg_match("/[.]+/",$string))< return (double)$string; >else < return (int)$string; >> if($string=="true") return true; if($string=="false") return false; return (string)$string; > 

I used this function to know if the number X is multiple of Y.

$number=6; $multipleof=2; if(gettype($number/$multipleof)=="integer") echo "The number ".$number." is multiple of ".$multipleoff."."; 

But the framework that i work returns always the input vars as strings.

You have some extra code. empty already tests for an empty string. Why are you using || $striing == «» ? Also, you’re casting a string to a string. PHP knows that «» is a string. That line could be rewritten as: if (empty($string)) return «» . Also, it doesn’t make sense to do return (bool)true/false . true and false are already booleans; they don’t need to be casted.

You must try to convert it in specified order:

  1. Check is double
  2. If double, this may be a integer, you must convert and compare this values.
  3. If not, this is char if lenght is == 1.
  4. If not, this is string.
  5. If string, try parse to bool.

You can’t use gettype because you may get string type of decimal writed in string.

Problem, and if the string has «12ab3»? it is string right? how can i know if the string has alphanumeric chars?

«12ab3» is not int, because have a alphanumeric, then algorithm not check double from it, they lenght is bigger than 1, then this is string, and cant parse it to bool. Result is string, and real result is string because «12ab3» is not a valid number.

Here is an updated version of this 9 year old function:

/** * Converts a form input request field's type to its proper type after values are received stringified. * * Function flow: * 1. Check if it is an array, if yes, return array * 2. Remove unused spaces * 3. Check if it is '0', if yes, return 0 * 4. Check if it is empty, if yes, return blank string * 5. Check if it is 'null', if yes, return null * 6. Check if it is 'undefined', if yes, return null * 7. Check if it is '1', if yes, return 1 * 8. Check if it is numeric * 9. If numeric, this may be a integer or double, must compare this values * 10. If string, try parse to bool * 11. If not, this is string * * (c) José Moreira - Microdual (www.microdual.com) * With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack) * * Found at: https://stackoverflow.com/questions/2690654/how-to-get-the-real-type-of-a-value-inside-string * * @param string $string * @return mixed */ function typeCorrected($string) < if (gettype($string) === 'array') < return (array)$string; >$string = trim($string); if ($string === '0') < // we must check this before empty because zero is empty return 0; >if (empty($string)) < return ''; >if ($string === 'null') < return null; >if ($string === 'undefined') < return null; >if ($string === '1') < return 1; >if (!preg_match('/[^0-9.]+/', $string)) < if(preg_match('/[.]+/', $string)) < return (double)$string; >else < return (int)$string; >> if ($string == 'true') < return true; >if ($string == 'false') < return false; >return (string)$string; > 

I am using it in a Laravel middleware to transform form values that were stringified by browser JavaScript’s FormData.append() back into their correct PHP types:

public function handle($request, Closure $next) < $input = $request->all(); foreach($input as $key => $value) < $input[$key] = $this->typeCorrected($value); > $request->replace($input); return $next($request); > 
  1. To create that, type in your CLI php artisan make:middleware TransformPayloadTypes .
  2. Then paste in the above handle function.
  3. Don’t forget to paste in the typeCorrected function also. I currently recommend making it a private function in your middleware class, but I don’t claim to be a super-expert.

You can imagine that $request->all() is an array of key/value pairs, and it comes in with all values stringified, so the goal is to convert them back to their true type. The typeCorrected function does this. I’ve been running it in an application for a few weeks now, so edge cases could remain, but in practice, it is working as intended.

If you get the above working, you should be able to do something like this in Axios:

// note: `route()` is from Tightenco Ziggy composer package const post = await axios.post(route('admin.examples.create', < . this.example, category: undefined, category_id: this.example.category.id, >)); 

Then, in your Laravel controller, you can do \Log::debug($request->all()); and see something like this:

[2020-10-12 17:52:43] local.DEBUG: array ( 'status' => 1, 'slug' => 'asdf', 'name' => 'asdf', 'category_id' => 2, ) 

With the key fact being that you see ‘status’ => 1, and not ‘status’ => ‘1’,

All of this will allow you to submit JSON payloads via Axios and receive non-nested values in your FormRequest classes and controllers as the actual payload types are mutated. I found other solutions to be too complex. This above solution allows you to submit flat JSON payloads from pure JavaScript easily (so far, haha).

Источник

Оцените статью