0

easy question but i can't find a solution.

I have an array:

array
   0 => 
     array
       1 => string '25' (length=2)
   1 => 
     array
       1 => string '27' (length=2)

And i need to get:

    array
  0 => string '25' (length=2)
  1 => string '27' (length=2)

Yea if course i could do:

foreach($result as $each) {
    $resultIds[]=$each[1];
}

But i am pretty sure i saw this week somewhere a function for it something like...

array_something('current',$result);

What will loop over the array as foreach and return the first element so the result will be the same as the foreach solution. But i can't find it or remember it.

*What is the name of the function ? *

3
  • array_column() could be useful if you're on PHP >= 5.5.0... there is a userland version for earlier versions of PHP Commented Oct 5, 2013 at 8:56
  • You can find all the array_something functions here: php.net/manual/en/ref.array.php Commented Oct 5, 2013 at 8:59
  • @barmar before i posted question i read about every function there... Commented Oct 5, 2013 at 9:03

2 Answers 2

2

You can use array_map or array_walk

example of array_map

<?php
function first($n)
{
    return $n[1];
}

$arr = array(
    array(1, 2, 4),
    array(1, 2, 3,),
);
var_export($arr);
// call internal function
$arr = array_map('current', $arr);
var_export($arr);

// call user function
$arr = array_map('first', $arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Thx this is the line $arr = array_map('current', $arr); i was looking for.. but its weird i would swear i tried array_map('current', $arr) before i posted question... hm... the mornings... :D Thx srain!
0

Please read manual here

$resultIds = array_map(function($arrEle) {
   return $arrEle[0];
}, $result);

array_map takes a function which gets passed each of the elements of the array in turn, it is called for each array element.

The function then needs to return whatever you want in the new array, in this case you are wanting the second element of the child array so we return $arrEle[1];

after the whole array has been iterated over it returns the new array.

3 Comments

Thx, but this is the same as foreach function too long i was looking for one line answer when i remember right what am i looking for.
@Trki you are probably thinking of array_column like Mark Baker mentions but you have to make sure the php version is 5.5 or greater or use the shim he links to.
I am using 5.3 but thx for notice for array_column function. I marked already answer what i was looking for. Thx anyway to all.

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.