Normally WordPress widget only allowed HTML tags. But using with this code you can also write PHP code in your widgets.
For it there are two solutions we have.
Solutions: 1 With simple 7 line Code.
Alternate Solution 2: Using with WordPress Plugin.
Here is a link of WordPress Plugin Directory: https://wordpress.org/plugins/php-code-widget/
You can easily download or install plugin.