0

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'),
);
2
  • 1
    There is no clever way without touching all the records I guess Commented May 27, 2014 at 8:30
  • 1
    If possible consider changing your data structure i.e. $details['type'] = array('bus','car','bike') Commented May 27, 2014 at 8:37

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

9 Comments

What you think about PHP's Prevoius versions ?
@InventorX Huh? How far back? PHP 5.3+ is usually fine? What do you mean?
Means PHP 5.3+ and less then PHP 5.5
array_column I guess is introduced before 5.5
Thanks for the solution h2ooooooo. many hosting providers are running php 5.2.x and so I think to use ramsey's alternate solution as you mentioned. Thanks again
|
0

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 ) 

1 Comment

use array_values() to reset the keys, and pretty nice solution really.

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.