0

I have an array in my PHP code which looks like this:

Array
(
[1] => Array
    (
        [subject_id] => 1
        [subject] => Math
        [default_selection] => 1
    )

[2] => Array
    (
        [subject_id] => 2
        [subject] => Physics
        [default_selection] => 0
    )

[3] => Array
    (
        [subject_id] => 3
        [subject] => Chemistry
        [default_selection] => 0
    )

[4] => Array
    (
        [subject_id] => 4
        [subject] => Biology
        [default_selection] => 0
    )

[5] => Array
    (
        [subject_id] => 5
        [subject] => Statistics
        [default_selection] => 0
    )

)

I would like to get the value of [subject] where [subject_id]= 2. Is there any direct/shortcut to do this in PHP or I need to run a foreach loop ?

4 Answers 4

2

If you need to do this just once on the same data, simply run a foreach loop:

<?php
    $foundArray = null;

    foreach ($array as $subArray) {
        if ($subArray['subject_id'] == 2) {
            $foundArray = $subArray;
            break;
        }
    }

    var_dump($foundArray);
?>

If you need to check subject_id's a lot with the same data (in the same request), you can associate your key with the subject_id and refer to it that way:

<?php
    $assoc = array();

    foreach ($array as $subArray) {
        $assoc[$subArray['subject_id']] = $subArray;
    }

    var_dump($assoc[2]);
    var_dump($assoc[3]);
    var_dump($assoc[4]);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

you can use array_map

Use this function:

function getSubject($subject) {
   if  ($subject['subject_id'] == 2) return $subject; 
}

Usage:

$subjects = array_map('getSubject', $array);
var_dump($subjects);

Reference: Get specific key value pair from multidimensional array

Comments

1

New in PHP 5.5 is the array_column() function, which will probably acheive what you're asking for (ie searching without using foreach()):

$searchForSubjectID = 2;
$index = array_search($searchForSubjectID, array_column($data, 'subject_id'));
$subject = $data[$index]['subject'];

print $subject;  //prints 'Physics'

If you're not on PHP 5.5 yet, there is a compatibility library for this function.

Comments

0

You can use array_filter to select the correct element:

<?php
    function getSecondSubject( $element ){
        return $element["subject_id"] == 2;
    }

    $only_subject_two = array_filter( $all_subjects, "getSecondSubject" );

    $subject = $only_subject_two["subject"];
?>

You can use some trickiness (like a variable) to make the subject_id you're looking for variable, if you need that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.