## Showing entries with tag "PHP".

Found 8 entries

### PHP: Calculate the percentage difference between two numbers2017-06-21

I need to compare two numbers and see if they're close to each other. Specifically I wanted to see if two numbers were within 3% of of each other. I wrote this simple function to calculate the percentage difference between two numbers, and optionally (with the third parameter) return `true` or `false` if they're within a given range. This should allow me to do a "fuzzy compare" on two numbers.

``````function percent_diff(\$a, \$b, \$ok_per = null) {
\$per_diff = abs((1 - (\$a / \$b)) * 100);

if (is_numeric(\$ok_per)) {
\$ok = \$per_diff < \$ok_per;

return \$ok;
}

return \$per_diff;
}``````

### PHP: Quote Word2015-01-13

I needed a function similar to Perl's qw. If you pass a string to this function it will return an array of the words, stripping any separating whitespace. If you pass true as the second parameter you will instead get a hash returning each word in a key/value pair.

``````function qw(\$str,\$return_hash = false) {
\$str = trim(\$str);

// Word characters are any printable char
\$words = str_word_count(\$str,1,"!\"#\$%&'()*+,./0123456789-:;<=>?@[\]^_`{|}~");

if (\$return_hash) {
\$ret = array();
\$num = sizeof(\$words);

// Odd number of elements, can't build a hash
if (\$num % 2 == 1) {
return array();
} else {
// Loop over each word and build a key/value hash
for (\$i = 0; \$i < \$num; \$i += 2) {
\$key   = \$words[\$i];
\$value = \$words[\$i + 1];

\$ret[\$key] = \$value;
}

return \$ret;
}
} else {
return \$words;
}
}``````

This is useful in the following scenarios:

``````\$str  = "Leonardo    Donatello    Michelangelo    Raphael";
\$tmnt = qw(\$str);

\$str = "
Leonardo       Blue
Donatello      Purple
Michelangelo   Orange
Raphael        Red
";
\$turtles = qw(\$str,true);``````

### PHP: Convert an array to a hash2017-11-28

I have a flat array that I want to convert to a hash so I can use it as a lookup table. There isn't an easy or clear way to do that in PHP so I wrote my own function:

``````function array_to_hash(array \$array, \$val = 1) {
\$ret = array_fill_keys(\$array, \$val);

return \$ret;
}``````

### PHP: Disable output buffering for the CLI2016-02-02

When writing a PHP application that's going to be run from the CLI often you will want to disable output buffering. With output buffering enabled you will not see any output until your terminal buffer (usually 1k or 4k) fills up . This is accomplished with the following PHP code at the beginning of your script:

``ob_get_flush();``

### PHP: IPV6 reverse DNS entries2016-01-27

Reverse DNS (PTR) entries in IPV6 are different than their IPV4 counterparts. To create an IPV6 reverse entry, you have to: fully expand the address, reverse it, and add a period between each character.

For example: `2001:db8::60` reverses to `0.6.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2`.

I wrote a simple PHP function to handle this for me:

``````function ipv6_ptr(\$ip_str) {
\$hex = unpack("H*hex", inet_pton(\$ip_str));
\$str = strrev(\$hex['hex']);
\$p   = str_split(\$str);
\$ret = join(".",\$p);

return \$ret;
}
``````

### PHP: is_exception()2015-10-08

I have an object in PHP that I need to check if it is an exception and act appropriately. Surprisingly PHP does not have an `is_exception()` function built in so I had to write my own:

``````function is_exception(\$obj,\$strict = false) {
if (!is_object(\$obj)) {
return false;
}

// It's some type of exception
if (\$obj instanceof Exception) {
if (!\$strict) {
return true;
// It's a raw exception
} elseif (get_class(\$obj) === "Exception") {
return true;
}
}

return false;
}``````

If you pass true as the second parameter it will only return true if it's a raw exception and not an inherited exception.

### PHP: Relative path between two directories2015-09-15

I need to calculate the relative path between two directories such that:

``````\$a = "/one/two/three/four/";
\$b = "/one/two/";``````

`\$a` to `\$b` has a relative path of `../../` and `\$b` to `\$a` has a relative path of `three/four/`. This function solves that problem very simply:

``````// Borrowed from http://php.net/manual/en/function.realpath.php#105876 and cleaned up
function relativePath(\$from, \$to, \$ps = DIRECTORY_SEPARATOR) {
\$arFrom = explode(\$ps, rtrim(\$from, \$ps));
\$arTo   = explode(\$ps, rtrim(\$to, \$ps));

while(count(\$arFrom) && count(\$arTo) && (\$arFrom == \$arTo)) {
array_shift(\$arFrom);
array_shift(\$arTo);
}

return str_pad("", count(\$arFrom) * 3, '..' . \$ps) . implode(\$ps, \$arTo);
}``````

### PHP: flat_var_export()2015-03-23

I needed to log a nested array to a file. To do this I needed to convert the array to a single line. After some searching I found improved_var_export() that converts a PHP array/object to a single line textual representation. I cleaned up some of the formatting and this is the result.

``````function flat_var_export(\$variable, \$return = false) {
if (\$variable instanceof stdClass) {
\$result = '(object) ' . flat_var_export(get_object_vars(\$variable), true);
} elseif (is_array(\$variable)) {
\$array = array();
foreach (\$variable as \$key => \$value) {
\$array[] = var_export(\$key, true) . ' => ' . flat_var_export(\$value, true);
}
\$result = 'array(' . implode(', ', \$array) . ')';
} else {
\$result = var_export(\$variable, true);
}

if (\$return) {
return \$result;
} else {
print \$result;
}
}``````