Cara menggunakan array is exist php

Additionally to the rich set of PHP array functions, the Yii array helper provides extra static methods allowing you to deal with arrays more efficiently.

Getting Values

Retrieving values from an array, an object or a complex structure consisting of both using standard PHP is quite repetitive. You have to check if key exists with

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
1 first, then if it does you're getting it, if not, providing default value:

class User
{
    public $name = 'Alex';
}

$array = [
    'foo' => [
        'bar' => new User(),
    ]
];

$value = isset($array['foo']['bar']->name) ? $array['foo']['bar']->name : null;

Yii provides a very convenient method to do it:

$value = ArrayHelper::getValue($array, 'foo.bar.name');

First method argument is where we're getting value from. Second argument specifies how to get the data. It could be one of the following:

  • Name of array key or object property to retrieve value from.
  • Set of dot separated array keys or object property names. The one we've used in the example above.
  • A callback returning a value.

The callback should be the following:

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});

Third optional argument is default value which is

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
2 if not specified. Could be used as follows:

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');

Setting values

As a result, initial value of

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
3 will be overwritten by new value

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]

If the path contains a nonexistent key, it will be created

The result will be

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]

Take a value from an array

In case you want to get a value and then immediately remove it from an array you can use

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
4 method:

$array = ['type' => 'A', 'options' => [1, 2]];
$type = ArrayHelper::remove($array, 'type');

After executing the code

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
5 will contain
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
6 and
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
7 will be
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
8. Note that unlike
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
9 method,
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
4 supports simple key names only.

Checking Existence of Keys

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
1 works the same way as array_key_exists except that it also supports case-insensitive key comparison. For example,

$data1 = [
    'userName' => 'Alex',
];

$data2 = [
    'username' => 'Carsten',
];

if (!ArrayHelper::keyExists('username', $data1, false) || !ArrayHelper::keyExists('username', $data2, false)) {
    echo "Please provide username.";
}

Retrieving Columns

Often you need to get a column of values from array of data rows or objects. Common example is getting a list of IDs.

$array = [
    ['id' => '123', 'data' => 'abc'],
    ['id' => '345', 'data' => 'def'],
];
$ids = ArrayHelper::getColumn($array, 'id');

The result will be

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
2.

If additional transformations are required or the way of getting value is complex, second argument could be specified as an anonymous function:

$result = ArrayHelper::getColumn($array, function ($element) {
    return $element['id'];
});

Re-indexing Arrays

In order to index an array according to a specified key, the

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
3 method can be used. The input should be either multidimensional array or an array of objects. The
$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
4 can be either a key name of the sub-array, a property name of object, or an anonymous function that must return the value that will be used as a key.

The

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
5 attribute is an array of keys, that will be used to group the input array into one or more sub-arrays based on keys specified.

If the

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
4 attribute or its value for the particular element is
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
2 and
$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
5 is not defined, the array element will be discarded. Otherwise, if
$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
5 is specified, array element will be added to the result array without any key.

For example:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
0

The result will be an associative array, where the key is the value of

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
0 attribute:

Anonymous function, passed as a

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
4, gives the same result:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
1

Passing

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
0 as a third argument will group
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
5 by
[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
0:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
2

The result will be a multidimensional array grouped by

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
0 on the first level and not indexed on the second level:

An anonymous function can be used in the grouping array as well:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
3

The result will be a multidimensional array grouped by

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
0 on the first level, by
[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
7 on the second level and indexed by
[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
8 on the third level:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
4

Building Maps

In order to build a map (key-value pairs) from a multidimensional array or an array of objects you can use

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]
9 method. The
[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
0 and
[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
1 parameters specify the key names or property names to set up the map. Optionally, one can further group the map according to a grouping field
[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
2. For example,

Multidimensional Sorting

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
3 method helps to sort an array of objects or nested arrays by one or several keys. For example,

$value = ArrayHelper::getValue($array, 'foo.bar.name');
5

After sorting we'll get the following in

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
4:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
6

Second argument that specifies keys to sort by can be a string if it's a single key, an array in case of multiple keys or an anonymous function like the following one:

Third argument is direction. In case of sorting by a single key it could be either

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
5 or
[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
6. If sorting by multiple values you can sort each value differently by providing an array of sort direction.

Last argument is PHP sort flag that could take the same values as the ones passed to PHP sort().

Detecting Array Types

It is handy to know whether an array is indexed or an associative. Here's an example:

HTML Encoding and Decoding Values

In order to encode or decode special characters in an array of strings into HTML entities you can use the following:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
7

Only values will be encoded by default. By passing second argument as

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
7 you can encode array's keys as well. Encoding will use application charset and could be changed via third argument.

Merging Arrays

You can use to merge two or more arrays into one recursively. If each array has an element with the same string key value, the latter will overwrite the former (different from array_merge_recursive()). Recursive merging will be conducted if both arrays have an element of array type and are having the same key. For integer-keyed elements, the elements from the latter array will be appended to the former array. You can use yii\helpers\UnsetArrayValue object to unset value from previous array or yii\helpers\ReplaceArrayValue to force replace former value instead of recursive merging.

For example:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
8

The result will be:

$value = ArrayHelper::getValue($array, 'foo.bar.name');
9

Converting Objects to Arrays

Often you need to convert an object or an array of objects into an array. The most common case is converting active record models in order to serve data arrays via REST API or use it otherwise. The following code could be used to do it:

The first argument contains the data we want to convert. In our case we're converting a

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
8 AR model.

The second argument is conversion mapping per class. We're setting a mapping for

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]
8 model. Each mapping array contains a set of mappings. Each mapping could be:

  • A field name to include as is.
  • A key-value pair of desired array key name and model column name to take value from.
  • A key-value pair of desired array key name and a callback which returns value.

The result of conversion above for single model will be:

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
0

It is possible to provide default way of converting object to array for a specific class by implementing Arrayable interface in that class.

Testing against Arrays

Often you need to check if an element is in an array or a set of elements is a subset of another. While PHP offers

$array = ['type' => 'A', 'options' => [1, 2]];
$type = ArrayHelper::remove($array, 'type');
0, this does not support subsets or
$array = ['type' => 'A', 'options' => [1, 2]];
$type = ArrayHelper::remove($array, 'type');
1 objects.

To aid these kinds of tests, yii\helpers\ArrayHelper provides and with the same signature as in_array().

Apa fungsi Array_key_exists?

Array adalah suatu variable yang dapat menyimpan lebih dari satu value. Dengan array ini kita bisa menyimpan data sementara pada variable tersebut.

Apa yang dimaksud dengan array di php?

Array dalam PHP adalah jenis struktur data yang memungkinkan kita untuk menyimpan beberapa elemen dari tipe data yang sama di bawah satu variabel tunggal.