devdarsh
devdarsh

Reputation: 95

Loop only certain array key in PHP

How can I loop to display the values of array key type without looping other keys because am have more than 500 array lines and reduce time.

$details = array(
    array('year' => '1990'),
    array('year' => '1995'),
    array('condition' => 'working'),
    array('type' => 'bus'),
    array('type' => 'car'),
    array('type' => 'bike'),
);

Upvotes: 0

Views: 85

Answers (2)

InventorX
InventorX

Reputation: 378

PHP Array

$details = array(
    array('year' => '1990'),
    array('year' => '1995'),
    array('condition' => 'working'),
    array('type' => 'bus'),
    array('type' => 'car'),
    array('type' => 'bike'),
);

Create Array that contain only "Type" index

$names = array_map(function ($v)
        { 
            return $v['type']; 
        }, 
        $details);

$names = array_filter($names);      

print_r($names);

Output

Array ( [3] => bus [4] => car [5] => bike ) 

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39532

You might be looking for array_column introduced in PHP 5.5 (however this still internally loops through the entire array to gather which sub arrays have this key):

<?php

$details = array_column($details, 'year');

print_r($details);

/*
    Array
    (
        [0] => 1990
        [1] => 1995
    )
*/

DEMO

For older versions of PHP the author himself has a polyfill on github.

Upvotes: 4

Related Questions