Can't Concatenate 2 Arrays in PHP

Can't concatenate 2 arrays in PHP

Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.

$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')

// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);

If the elements in your array used different keys, the + operator would be more appropriate.

$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');

// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;

Edit: Added a code snippet to clarify

Merge two arrays together in PHP?

i think you have same length for all array for steps and instructions
here you need to store that two array in another array with the particular elements of those array with same key

//array that contain steps
$array1=array('Prep','Cook','Serve');
//array that contain instructions
$array2=array('In a large mixing bowl, crack 2 large eggs.','In a medium-sized frying pan or griddle, heat up a tablespoon of unsalted butter...','When done, transfer the french toast onto a plate.');
//calculate length of any one array because length is same
$length=count($array1);
//store that particular element in new array with keys
$array3=array();
for($i=0;$i<$length;$i++){
$array3[$i]['name']=$array1[$i];
$array3[$i]['text']=$array2[$i];
//you can add that another key and value here like $array3[$i]['image']='your image link';
}
//print the final array
echo '<pre>';
print_r($array3);

php How to concatenate 2 arrays in one array

Try this

<?php
$list = array(array('white','Black'), array('S','L','M'));
$result = array();
foreach ($list[0] as $k) {
foreach ($list[1] as $t) {
$result[] = $k.','.$t;
}
}
var_dump($result);
?>

Concatenate values of two arrays

You need a foreach loop inside a foreach loop. (Actualy, you will have to loop through both arrays to get a concatenated product of both arrays, you don't actually need two foreach loops). You could mix: whiles, foreach, for, or php filter/intersect array functions

Example

$array1 = array(1,2);
$array2 = array(3,4);
$result = array();

foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = $item1.','.$item2;
}
}

https://eval.in/215001

your result array Length will be array1.Length * array2.Length

2d arrays

You could also put an array inside an array like this:

$array1 = array(1,2);
$array2 = array(3,4);
$result = array();

foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = array($item1, $item2);
}
}
//$result[0][0] = 1 -- $result[0][1] = 3
//$result[1][0] = 1 -- $result[1][1] = 4
//$result[2][0] = 2 -- $result[2][1] = 3
//$result[3][0] = 2 -- $result[3][1] = 4

We call this a 2d (2 dimensional) array, because you could grapicly display this as a grid, like displayed here above. If you would put an Array, inside an Array inside an Array, you would call this a 3 dimensional array, etc.

print_r($result); in php:

Array
(
[0] => Array
(
[0] => 1
[1] => 3
)

[1] => Array
(
[0] => 1
[1] => 4
)

[2] => Array
(
[0] => 2
[1] => 3
)

[3] => Array
(
[0] => 2
[1] => 4
)

)

error when I concatenate two strings in an array - PHP

This is because you're doing this as part of the class property's declaration which isn't possible due to the fact that:

...declaration may include an
initialization, but this
initialization must be a constant
value--that is, it must be able to be
evaluated at compile time and must not
depend on run-time information in
order to be evaluated.

See the PHP manual properties page for more information.

However, you could set this property as required within your constructor and all will be well:

class TestClass {
public $Options;

function __construct() {
$this->Options = array (0 => 'aaaaa' . 'bbbbb');
}
}

Can't concatenate on an array - Parse error: syntax error

For some reason the concatenation is not working when the array is in a class, but outside a method.

class Foo {
$upload = array(
'path' => FILEPATH . 'assets/uploads/', unexpected '.', expecting ')'
'allowed_types' => 'gif|jpg|png'
);
}

You have to set it inside a method in order to work

class Foo{
public function daa(){
$this->upload = array(
'path' => FILEPATH . 'assets/uploads/', unexpected '.', expecting ')'
'allowed_types' => 'gif|jpg|png'
);
}
}

PHP: merge two arrays while keeping keys instead of reindexing?

You can simply 'add' the arrays:

>> $a = array(1, 2, 3);
array (
0 => 1,
1 => 2,
2 => 3,
)
>> $b = array("a" => 1, "b" => 2, "c" => 3)
array (
'a' => 1,
'b' => 2,
'c' => 3,
)
>> $a + $b
array (
0 => 1,
1 => 2,
2 => 3,
'a' => 1,
'b' => 2,
'c' => 3,
)

Merge two arrays into one array (identic keys)

You can try in this way:

$array1 = array( array('accordion_title'=>'Title 1'),array('accordion_title'=>'Title 2') );
$array2 = array( array('accordion_content'=>'Content 1'),array('accordion_content'=>'Content 2') );

$array3 = array();
foreach( $array1 as $key => $array )
{
$array3[] = array( key($array) => current($array), key($array2[$key]) => current($array2[$key]) );
}

print_r( $array3 );

This is the output:

Array
(
[0] => Array
(
[accordion_title] => Title 1
[accordion_content] => Content 1
)

[1] => Array
(
[accordion_title] => Title 2
[accordion_content] => Content 2
)

)

Updated:

With this function you can combine infinite arrays (not only two), even if they have different sizes:

/*   Groups passed arrays in an array of associative arrays with same keys and values
*
* @example $array1 = array( array('a'=>'val1'),array('a'=>'val2') );
* $array2 = array( array('b'=>'val3'),array('b'=>'val4') );
* $array3 = array( array('c'=>'val5'),array(),array('c'=>'val6') );
* multiArrayCombine( $array1, $array2, $array3 );
* return: array
* (
* 0 => array('a'=>'val1','b'=>'val3','c'=>'val5'),
* 1 => array('a'=>'val2','b'=>'val4'),
* 2 => array('c'=>'val6')
* )
*
* @param array $array1[, $array2[, $array3...]]
*
* @option const T_OBJECT_CAST cast returned assoc arrays as stdObject
*
* @return array
*/
function multiArrayCombine()
{
/* Get all passed parameters and T_OBJECT_CAST option: */
$args = func_get_args();
$asObject = ( T_OBJECT_CAST == end($args) );
if( $asObject ) array_pop( $args );

$retval = array(); # Init array to be returned

/* Retrieve highest passed arrays key: */
$max = 0;
foreach( $args as $array ) $max = max( $max, max( array_keys($array) ) );

/* Loop for each arrays key: */
for( $i=0; $i<=$max; $i++ )
{
/* Init associative array to add: */
$add = array();

/* Process actual key ($i) of each passed array: */
foreach( $args as $array )
{
/* If the key ($i) exists, add each passed array: */
if( isset($array[$i]) AND is_array($array[$i]) )
{
foreach( $array[$i] as $key => $val )
{ $add[$key] = $val; }
}
}

/* Add the obtained associative array to return array */
if( $asObject ) $retval[] = (object) $add;
else $retval[] = $add;
}

return $retval;
}

So, with the following code (three arrays):

$array1 = array( array('accordion_title'=>'Title 1'),array('accordion_title'=>'Title 2') );
$array2 = array( array('accordion_content'=>'Content 1'),array('accordion_content'=>'Content 2') );
$array3 = array( array('accordion_date'=>'Date 1'),array(),array('accordion_date'=>'Date 3') );

print_r( multiArrayCombine( $array1, $array2, $array3 ) );

the output is:

Array
(
[0] => Array
(
[accordion_title] => Title 1
[accordion_content] => Content 1
[accordion_date] => Date 1
)

[1] => Array
(
[accordion_title] => Title 2
[accordion_content] => Content 2
)

[2] => Array
(
[accordion_date] => Date 3
)
)

eval.in demo

Updated 2:

  1. Now the function return all passed values of each rows, not only the first;
  2. Added option T_OBJECT_CAST: passing constant T_OBJECT_CAST after the list of arrays, rows of returned array as formatted as stdObjects instead of arrays.

Explanation:

To allow not predetermined arguments, I don't format function as multiArrayCombine( $arg1, $arg2, ... ), I use instead the func_get_args() function, that "allow user-defined functions to accept variable-length argument lists".

First of all (in the latest update), I check if the last argument is the predefined constant T_OBJECT_CAST: if it is, I set $asObject to True, then I pop-it off the end of arguments array; now in the $args variable I have an array with each passed arrays.

Next step: I retrieve the max key value of all passed arrays; i choose this way instead of more comfortable foreach( $array1 as $row ) to avoid to omit values if one of the other arrays have more rows than the first. Eventually not numeric keys are omitted.

Then, the main loop: I process each row of originals arrays and I add their keys and values to row that will added to returned array. If there are duplicated keys, only the last is returned.

After processing each array, i add the obtained row (converted to object if this option is passed) to returning array.

That's all!


Globish here, i'm sorry

Combine 2 Arrays In Foreach in PHP

You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:

$combined = array_combine($digits, $results);

foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}


Related Topics



Leave a reply



Submit