Griff
Griff

Reputation: 1747

Check an array value is set from another arrays values PHP?

I have an array like so which is built automatically and dynamic in length.

$arr = array('k1','k2','k3','k4',);

And I have an already existing array $exArr, how can I check dynamically the same as doing this below;

if($exArr[$arr[0]][$arr[1]][$arr[2]][$arr[3]]) echo 'IT EXISTS';

Bearing in mind that the dynamically built array could have just one or up to and over 10 sequential keys to check.

Thanks

EDIT

To be more clear I have an array which is dynamic but will only contain values. It could be any length.

The dynamically built array corresponds with another array's keys, I need a way to check that all the values in the dynamically built array are correct and point to a value, example;

$dynamic = array('one', 'two', 'three');

$existing = array('one' => array('two' => array('three' => array(true))));

The above would evaluate to true as the statement below is correct,

if($existing[$dynamic[0]][$dynamic[1]][$dynamic[2]]) echo 'WOO';

The trouble I am having is that the dynamic array is just that! It could be one in length or 50. So having a plain old if statement isn't going to work here.

Thanks again

Upvotes: 0

Views: 246

Answers (2)

Daniel
Daniel

Reputation: 4946

This searches through a multidimensional array for keys in your unique array A. The keys found are stored in array C. Hope this helps.

<?php

$arrayA = array("a", "b", "c", "h", "p");

$arrayB = array("a" => array("g" => array("c" => array("d" => "x"))));
$arrayC = array();

function searchKeys($array) {
    global $arrayA;
    global $arrayC;

    foreach ($array as $key => $value) {

        if (in_array($key, $arrayA)) {
            $arrayC[] = $key;
        }

        if (is_array($value)) {
               searchKeys($value);
        }

    }
}

searchKeys($arrayB, $arrayA);
print_r($arrayC);
?>

Upvotes: 0

Cito
Cito

Reputation: 1709

<?php
$dynamic = array('one', 'two', 'three');

$existing = array('one' => array('two' => array('three' => array(true))));

function check($dynamic, $existing) {
    foreach ($dynamic as $key ) {
        if (!isset ($existing [$key])) {
                    // return false;
            throw new Exception("{$key}");
        }
        $existing = $existing [$key];
    }
    return true;
}

try {
    check($dynamic, $existing);
} catch (exception $e) {
    echo "Invalid! On key: {$e->getMessage()}\n\n"; exit;
}

echo "Valid if it gets here!\n\n";

$dynamic = array('one', "invalid", 'two', 'three');

try {
    check($dynamic, $existing);
} catch (exception $e) {
    echo "Invalid! On key: {$e->getMessage()}\n\n"; exit;
}

echo "Valid if it gets here!\n\n";

Test: http://eval.in/12819

You can replace the throw for return false

Upvotes: 1

Related Questions