Skip to content

Instantly share code, notes, and snippets.

@stevenslack
Last active March 25, 2022 15:12
Show Gist options
  • Save stevenslack/5a5adb2f219f23b5d444afae27f3916c to your computer and use it in GitHub Desktop.
Save stevenslack/5a5adb2f219f23b5d444afae27f3916c to your computer and use it in GitHub Desktop.
Calculate the height for a specific width and aspect ratio.
<?php
/**
* Calculate the height for a specific width and aspect ratio.
*
* @param int $width The width used to generate a height for the aspect ratio.
* @param string $aspect_ratio The aspect ratio with the ':' as a delimiter. Example: '16:9'.
* @return string The calculated aspect ratio height.
*/
function calc_aspect_ratio_height( int $width = 100, string $aspect_ratio = '16:9' ): string {
// If the aspect ratio is invalid use the default value of 16:9.
if ( empty( $aspect_ratio ) || false === strpos( $aspect_ratio, ':' ) ) {
$aspect_ratio = '16:9';
}
// Split the string between the delimiter in order to run the aspect ratio calculation.
list( $divisor, $dividend ) = explode( ':', $aspect_ratio );
// Cast the divisor and dividend as integers.
$dividend = intval( $dividend );
$divisor = intval( $divisor );
$quotient = $dividend / $divisor;
// Check for empty values for quotient assignment and fallback to 16:9 otherwise.
if ( ( empty( $divisor ) || is_nan( $divisor ) ) || ( empty( $dividend ) || is_nan( $dividend ) ) ) {
$quotient = 9 / 16;
}
// In the case that the quotient is invalid or not a number, use the default aspect ratio.
if ( is_nan( $quotient ) ) {
$quotient = 9 / 16;
}
$product = $quotient * intval( $width );
// If this is a float then add at 2 decimal points to number format.
$decimals = is_float( $product ) ? 2 : 0;
// Return a regular number format with at least 2 decimal points if the product is a float.
return number_format( $product, $decimals );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment