Category Archives: PHP

PHP Snippet – array_splice_assoc(…)

Recently I was working on something that required inserting key-value pairs into an array after a specific key in PHP. As I was looking through stackoverflow answers I realized that there was no awesome answer that really jumped out at me. Therefore I decided to take a few minutes to just write my own array_splice_assoc() function to get the job done:

As you can see this function takes the same parameters that array_splice() does but the difference is that the offset can be a string in this key which refers to the key after which the new array elements should be inserted.

One important thing to note is that if you try to insert a key-value pair in which the key exists before or at the offset, your key-value pair will not be inserted. On the other hand if you try to insert a key-value pair in which the key exists after offset, your value will replace the previous one.

Have fun! :cool:

PHP – Re-indexing 2D Array By A Specific Key

Today I was working on a personal project and wanted to be able to use a native PHP function to re-index a 2D array so that the key for each sub-array was pulled from a value in that sub-array. Unfortunately I wasn’t able to find a way to simply do it natively although it may exist. Therefore I wrote this array_by_column() function:

To use it you can simply supply the 2D array as the first argument and the key (or column name) as the second parameter.

PHP – Problem with issetor()

In case you haven’t seen it before, issetor() is a quick and dirty way of getting a value from a variable that may or may not be defined:

function issetor(&$var, $default=NULL) {
  return isset($var) ? $var : $default;
}

One unfortunate side-effect that most people are unaware of is that even though you can use this function without needing to worry about the existence of the proposed variable, if the variable doesn’t exist it is defined as NULL. Therefore the following type of strange case could occur:

$arr = [1,2,3];
echo count($arr); // 3
$fourth = issetor($arr[4]);
echo count($arr); // 4

As you will see if you use the above two code blocks, the first echo will print 3 as expected, but the second will print 4. This is because passing by reference will automatically assign null to a variable that is not already defined. Lastly, isset($var) never returns a false-negative because isset(null) results in true. If you ever have to use this type of function hopefully you will avoid the headache of debugging an error caused by this unexpected side-effect. :cool: