io-developer/php-keyget

PHP KeyGet solves routine actions like 'Get array value by key or default if not exists' and 'Ensure array has key or set to default'

1.0.1 2018-06-08 12:16 UTC

This package is not auto-updated.

Last update: 2024-11-04 16:37:56 UTC


README

Build Status Packagist

Library solves routine actions like:

  • Get array value by key/index if exists or return default value
  • Set array key/index if not exists

Installation

System requirements:

PHP >= 5.0 (tests for 7.1 up to nightly)

Composer:
composer require io-developer/php-keyget

or composer.json:

"require": {
    "io-developer/php-keyget": "*"
}

Examples

Get value by key of default if not exists
<?php

$arr = ['foo' => 'bar'];
var_dump([
    key_get($arr, 'foo'), // 'bar'
    key_get($arr, 'baz'), // null
    key_get($arr, 'baz', 'Ooops!'), // 'Ooops!'
]);
Set value if key not exists
<?php

$arr = ['foo' => 'bar'];

key_setdefault($arr, 'foo', 'meow');
var_dump($arr);  // no changes

key_setdefault($arr, 'baz', 'meow');
var_dump($arr);  // ['foo' => 'bar', 'baz' => 'meow']