S
S
serikd2016-05-04 16:28:54
PHP
serikd, 2016-05-04 16:28:54

Is there such a function in PHP?

Is there a standard function that extracts only the required values ​​from a given array by keys?

private static function extractOnly(array $parsed, array $params)
    {
        $result = [];
        foreach ($params as $key) {
            if (array_key_exists($key, $parsed)) {
                $result[$key] = $parsed[$key];
                continue;
            }

            throw new \ErrorException('Key "' . $key . '" do not exists in array');
        }

        return $result;
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Osher, 2016-05-04
@serikd

array_intersect_key($parsed, array_flip($params));

R
Rsa97, 2016-05-04
@Rsa97

<?php
  $list = array("hello", "privet");
  $arr = array("hello" => "Vasya", "privet" => "Petya", "zdorovo" => "Misha");
  $arr = array_filter($arr, function($key) use ($list) { return in_array($key, $list); } , ARRAY_FILTER_USE_KEY);
  print_r($arr);
?>

S
shagguboy, 2016-05-04
@shagguboy

php.net/manual/en/function.array-intersect-key.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question