WordPress.org

Make WordPress Core

Opened 5 years ago

Closed 4 years ago

#31820 closed enhancement (fixed)

get_option() returns Integers as strings

Reported by: golderweb Owned by: boonebgorges
Milestone: 4.5 Priority: normal
Severity: normal Version: 4.1.1
Component: Options, Meta APIs Keywords: has-patch
Focuses: docs Cc:
PR Number:

Description

For Options which are declared to be Integers there, get_options() always returns the Integer as a string like this:

$value = get_option( 'comment_max_links' );
var_dump( $value );


Result:

string '2'

Maybe it would be more intuitive if get_option would return an integer since is_int() will return "FALSE" on "integer-strings".
Otherwise the Option_Reference and the Function Reference should be changed to something like "numeric-string".

Attachments (1)

31820.diff (558 bytes) - added by MikeHansenMe 4 years ago.

Download all attachments as: .zip

Change History (6)

#2 @boonebgorges
5 years ago

See also #22192. All scalar values passed to update_option() are ultimately stored in a 'longtext' field in the database, which means that they're retrieved as strings. There's nothing we can really do about this, given the current schema - it doesn't seem safe to me to assume that anything numeric should be cast to int/float during get_option(). We could probably make this a bit clearer in the inline documentation.

@MikeHansenMe
4 years ago

#3 @MikeHansenMe
4 years ago

  • Keywords has-patch added

31820.diff changes the doc to show the return value is a string. If you do need to force something to be an int you could do something like

function force_int( $value ) {
   if ( is_numeric( $value ) ) {
       return (int) $value;
   }
}
add_filter( 'option_your_option_name', 'force_int' );

https://codex.wordpress.org/Plugin_API/Filter_Reference/option_(option_name)

Last edited 4 years ago by MikeHansenMe (previous) (diff)

#4 @boonebgorges
4 years ago

  • Focuses docs added
  • Milestone changed from Awaiting Review to 4.5

31820.diff won't work, because non-scalar values - objects, arrays, anything serializable - are not returned as strings.

The suggestion made in 3 by @MikeHansenMe is a good one. I'll add a bit of inline documentation that gestures at it.

#5 @boonebgorges
4 years ago

  • Owner set to boonebgorges
  • Resolution set to fixed
  • Status changed from new to closed

In 36234:

Clarify return types in get_option() documentation.

The new note specifies that scalar values will always be returned as strings.

Fixes #31820.

Note: See TracTickets for help on using tickets.