Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join array values in PHP

Tags:

php

I have a PHP array:

array
  0 => 
    array
      'cid' => string '18427' (length=5)
  1 => 
    array
      'cid' => string '17004' (length=5)
  2 => 
    array
      'cid' => string '19331' (length=5)

I want to join the values so I can get a string like this:

18427,17004,19331

I tried the implode PHP function, But I get an error:

A PHP Error was encountered

How can join only the values which are in cid?

like image 610
LiveEn Avatar asked Apr 02 '13 07:04

LiveEn


People also ask

How do you merge arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

What is use of join in PHP?

The join() function is built-in function in PHP and is used to join an array of elements which are separated by a string. Syntax string join( $separator, $array) Parameter: The join() function accepts two parameter out of which one is optional and one is mandatory.

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );


1 Answers

You have to map the array values first:

echo join(',', array_map(function($item) {
    return $item['cid'];
}, $arr));

Without closures it would look like this:

function get_cid($item)
{
  return $item['cid'];
}

echo join(',', array_map('get_cid', $arr));

See also: array_map()

like image 114
Ja͢ck Avatar answered Oct 16 '22 18:10

Ja͢ck