1

I am trying to pull dynamic element in single array but result is not showing properly
Ex:

$array  =array();
$element="'abc1','abc2'";
$array=array('abc',$element);

//I want result like that:

array[
     [0]=>abc,
     [1]=>abc1,
     [2]=>ab
    ]
2
  • what is it showing? what do you want it to show Commented Sep 4, 2017 at 12:56
  • i want to pull dymanic element sing variable in array Commented Sep 4, 2017 at 13:08

2 Answers 2

1

If you need to parse a string of elements to an array you can use one of the csv functions. You may then merge your arrays.

$array   = array('abc');
$string_elements = "'abc1','abc2'";
$array_elements = str_getcsv($string_elements, ',', "'");
$array = array_merge($array, $array_elements);
var_export($array);

Output:

array (
    0 => 'abc',
    1 => 'abc1',
    2 => 'abc2',
  )

Alternatively to add each array element to the end of another array you can push them like so using a splat:

array_push($array, ...$array_elements);
Sign up to request clarification or add additional context in comments.

Comments

0

According to my understanding, $element is storing string not an array so even if you try to get output it will display in following format

Array
   (
     [0] => abc
     [1] => 'abc1','abc2'
   )

Instead of this you can store array in $element variable and use array_merge() function to get required output e.g.

$element = array('abc1','abc2');
$array   = array('abc');
$result  = array_merge($array,$element);

// Output

Array
(
    [0] => abc
    [1] => abc1
    [2] => abc2
)

Comments

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.