~ Apr 15, 2021

3 Handy PHP Functions

Photo by Ben on Unsplash

PHP has a lot of great functions and these are some I like to use and I will show you why.


in_array($needle, $haystack)

This function is great for comparing a value to multiple options, especially while using it for if statements.

// Before
if ($type === 'photo' || $type ===  'image' || $type ===  'file') {
    ...
}

// After
if (in_array($type, ['photo''image''file'], $strict true)) {
    ...
}

array_column($array, $column, $index)

This is a handy function to turn an already existing array into a key-value array that can be used for looping through and use for a select field for example. This is for example really powerful if you are fetching a list from an API and you want the user to select one of the options for the next API call. The only downside is that you can't use it on a multi-layered array, for this I would advise using the collection class of Laravel

$array = [
    [
        
'id' => 12,
        
'name' => 'John',
        
'email' => 'john@example.com',
    ],
    [
        
'id' => 34,
        
'name' => 'Jane',
        
'email' => 'jane@example.com',
    ],
]

// Keep in mind that the last argument is optional,
// if you don’t pass it through it will start at zero
$returned array_column($array'name''id');

// Will result into this
[
    
12 => 'John',
    
34 => 'Jane',
];

array_merge(...$arrays)

This is great if you have a fixed set of options that you want to overwrite based on some conditionals. I use this a lot in test files when I want to create multiple records that have the same default values for 90% of the time.

protected function createPost($amount 2$data = [])
{
    return 
Post::factory($amount)->create(array_merge([
        
// This will be the default data that can be overwritten.
        
'user_id' => $this->userId,
    ], 
$data));
}

© 2024 Gertjan Roke. All rights reserved. - ❤️ Since 1990