How to join string after last array value? [duplicate] - php

This question already has answers here:
How add a link on comma separated multidimensional array
(2 answers)
Closed 7 months ago.
I am trying to generate a string from an array. Need to concatenate the array values with a small string AFTER the value. It doesn't work for the last value.
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
echo($string_from_array);
// expected output: saladbar, winebar, beerbar
// output: saladbar, winebar, beer

You can achieve it a few different ways. One is actually by using implode(). If there is at least one element, we can just implode by the delimiter "bar, " and append a bar after. We do the check for count() to prevent printing bar if there are no results in the $symbols array.
$symbols = array_column($data, "symbol");
if (count($symbols)) {
echo implode("bar, ", $symbols)."bar";
}
Live demo at https://3v4l.org/ms5Ot

You can also achieve the desired result using array_map(), as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($v) => "{$v}bar",
array_column($data, 'symbol')
)
);
See live code
Array_map() takes every element of the array resulting from array_column() pulling out the values from $data and with an arrow function, appends the string "bar". Then the new array yielded by array_map has the values of its elements joined with ", " to form the expected output which is then displayed.
As a recent comment indicated you could eliminate array_column() and instead write code as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($row) => "{$row['symbol']}bar",
$data
)
);
See live code
Note while this 2nd way, may appear more direct, is it? The fact is that as array_map iterates over $data, the arrow function contains code that requires dereferencing behind the scenes, namely "$row['symbol']".

The join() function is an alias of implode() which
Returns a string containing a string representation of all the array
elements in the same order, with the glue string between each element.
So you need to add the last one by yourself
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
if(strlen($string_from_array)>0)
$string_from_array .= "bar";
echo($string_from_array);

You can use array_column and implode
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$res = implode("bar,", array_column($data, 'symbol'))."bar";
Live Demo

Try this:
$symbols = array_column($data, 'symbol');
foreach ($symbols as $symbol) {
$symbol = $symbol."bar";
echo $symbol;
}
btw, you can't expect implode to do what you expect, because it places "bar" between the strings, and there is no between after the last string you get from your array. ;)

Another way could be using a for loop:
$res = "";
$count = count($data);
for($i = 1; $i <= $count; $i++) {
$res .= $data[$i]["symbol"] . "bar" . ($i !== $count ? ", " : "");
}
echo $res; //saladbar, winebar, beerbar
Php demo

Related

How to add $_POST values in a multi-dimensional array (PHP)?

I know there may be sources for this out there but I'v tried everything and I'm still not getting the proper solution. That why I'm asking for you help out here.
I have a $_POST array and I want to put values in a an array. Here is the final out I want:
$response = [
['category' => 2, 'value' => "june"],
['category' => 5, 'value' => "may"],
['category' => 8, 'value' => "april"]
]
Here is the catch,the $_POST contains a value of an integer with a space in between and then a string eg '2 june', '5 may' etc
When I get this value, I split it using explode then I try to add the individual values into the response array. This is only adding just one result.
What I tried:
$response = [];
foreach ($_POST as $key => $value) {
$split = explode(" ", $value);
$result = ['category' => $split[0], 'value' => $split[1]];
$response[] = $result;
}
for some reason, the results are not as suggested above. Any ideas and suggestion will be appreciated.
Basically, problem is in the $_POST. This is global array with submitted key-values data. You should NOT use
foreach ($_POST as $key => $value) {
for parsing your data without any checks. This data is submitted by user, and not always they will have format you're waiting for.
For example, if you have a variable "dates" in your HTML form, you should be ready that $_POST['dates'] will be an array of all of your '5 june', '7 july', etc. Don't forget to check and validate all user data you received. It's important by security reason too.
Your code (foreach body, without condition) is ok, I've checked it. Try to set print_r() before explode() you will see that your're working with an array, not with a string.
Your question doesn't have an issue with processing the data into the correct resulting array. The onus falls on $_POST not holding the expected data.
All answers to this question are powerless to fix your $_POST data because no html form was supplied with your question. The only potential value that can be offered is to refine your array building process.
Here are two methods that improve your process by reducing the number of declared variables:
Demonstration uses $a=array('2 june','5 may','8 april'); to represent your $_POST array.
One-liner in a foreach loop:
foreach($a as $v){
$r[]=array_combine(["category","value"],explode(" ",$v));
}
One-liner with no loop:
$r=array_map(function($v){return array_combine(["category","value"],explode(" ",$v));},$a);
Using either process the resulting $r will be:
array (
0 =>
array (
'category' => '2',
'value' => 'june',
),
1 =>
array (
'category' => '5',
'value' => 'may',
),
2 =>
array (
'category' => '8',
'value' => 'april',
),
)
References for used functions:
explode() , array_combine() , array_map()
Try this one:
$response = [];
// just for example use this one
$data = "2 june, 5 may, 7 july";
$temp = explode(",", $data);
// and you can use this one for your case
/*$data = $_POST['var_name']; // var_name is your variable name from $_POST
$temp = explode(",", $data);*/
foreach ($temp as $key => $value) {
$split = explode(" ", trim($value));
foreach ($split as $val) {
$result = ['category' => $split[0], 'value' => $split[1]];
}
$respon[] = $result;
}
echo "<pre>";
echo print_r($respon);
echo "</pre";
the output:
Array
(
[0] => Array
(
[category] => 2
[value] => june
)
[1] => Array
(
[category] => 5
[value] => may
)
[2] => Array
(
[category] => 7
[value] => july
)
)
$response = array();
foreach ($_POST as $key => $value) {
$split = '';
$split = explode(" ", $value);
$result = array('category' => $split[0], 'value' => $split[1]);
$response[] = $result;
}

Search PHP array of arrays using an array value and then update other array values in the matching array

I have a string stored in WordPress MySQL database Meta field as serialized string of array of arrays like this:
a:4:{i:0;a:8:{s:19:"ab-variation-letter";s:1:"B";s:18:"ab-variation-title";s:6:"bbbbbb";s:28:"ab-variation-wysiwyg-editor-";s:12:"bbbbbbbbbbbb";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:1;a:8:{s:19:"ab-variation-letter";s:1:"C";s:18:"ab-variation-title";s:5:"ccccc";s:28:"ab-variation-wysiwyg-editor-";s:17:"ccccccccccccccccc";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:2;a:8:{s:19:"ab-variation-letter";s:1:"D";s:18:"ab-variation-title";s:8:"dddddddd";s:28:"ab-variation-wysiwyg-editor-";s:1:"d";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:3;a:8:{s:19:"ab-variation-letter";s:1:"E";s:18:"ab-variation-title";s:8:"eeeeeeee";s:28:"ab-variation-wysiwyg-editor-";s:30:"eeeeeee eeeeeeeeeeeee eeeeeeee";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}}
When I unserialize that string above it looks like this below...
array (
0 =>
array (
'ab-variation-letter' => 'B',
'ab-variation-title' => 'bbbbbb',
'ab-variation-wysiwyg-editor-' => 'bbbbbbbbbbbb',
'ab-variation-conversion-count' => '',
'ab-variation-views' => '',
'ab-variation-start-date' => '',
'ab-variation-end-date' => '',
'ab-variation-winner' => '',
),
1 =>
array (
'ab-variation-letter' => 'C',
'ab-variation-title' => 'ccccc',
'ab-variation-wysiwyg-editor-' => 'ccccccccccccccccc',
'ab-variation-conversion-count' => '',
'ab-variation-views' => '',
'ab-variation-start-date' => '',
'ab-variation-end-date' => '',
'ab-variation-winner' => '',
),
2 =>
array (
'ab-variation-letter' => 'D',
'ab-variation-title' => 'dddddddd',
'ab-variation-wysiwyg-editor-' => 'd',
'ab-variation-conversion-count' => '',
'ab-variation-views' => '',
'ab-variation-start-date' => '',
'ab-variation-end-date' => '',
'ab-variation-winner' => '',
),
3 =>
array (
'ab-variation-letter' => 'E',
'ab-variation-title' => 'eeeeeeee',
'ab-variation-wysiwyg-editor-' => 'eeeeeee eeeeeeeeeeeee eeeeeeee',
'ab-variation-conversion-count' => '',
'ab-variation-views' => '',
'ab-variation-start-date' => '',
'ab-variation-end-date' => '',
'ab-variation-winner' => '',
),
)
based on this array of arrays above. I want to be able to search for the array that has ab-variation-letter' => 'C' and then be able to update any of the other array key values on that matching array. When done I will need to re-serialize back into a string so I can save it back to the Database table again.
I want to build this PHP function below to be able to take my serialized string of array of arrays and search those arrays for an array that has a key/value matching the passed in $array_key string and then update another keyvalue in that same array and then reserialize the whole thing again.
function updateAbTestMetaData($post_id, $meta_key, $meta_value, $array_key, $new_value){
//get serialized meta from DB
$serialized_meta_data_string = 'a:4:{i:0;a:8:{s:19:"ab-variation-letter";s:1:"B";s:18:"ab-variation-title";s:6:"bbbbbb";s:28:"ab-variation-wysiwyg-editor-";s:12:"bbbbbbbbbbbb";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:1;a:8:{s:19:"ab-variation-letter";s:1:"C";s:18:"ab-variation-title";s:5:"ccccc";s:28:"ab-variation-wysiwyg-editor-";s:17:"ccccccccccccccccc";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:2;a:8:{s:19:"ab-variation-letter";s:1:"D";s:18:"ab-variation-title";s:8:"dddddddd";s:28:"ab-variation-wysiwyg-editor-";s:1:"d";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:3;a:8:{s:19:"ab-variation-letter";s:1:"E";s:18:"ab-variation-title";s:8:"eeeeeeee";s:28:"ab-variation-wysiwyg-editor-";s:30:"eeeeeee eeeeeeeeeeeee eeeeeeee";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}}';
//un-serialize meta data string
$meta_data_arrays = unserialize($serialized_meta_data_string);
// search array of arrays $meta_data_arrays for array that has a key == $array_key // 'ab-variation-letter' === 'D'
// update the value of any other key on that matching array
// re-serialize all the data with the updated data
}
The end result should allow me to find the array with key 'ab-variation-letter' === 'C' and update the key/value in that matching array with key 'ab-variation-title' and update its current value from 'ccccc' to 'new value' and then re-serialize the whole entire array of arrays back into the original string with only the updated array data updated/
Perhaps throwing together a recursive function that can make use of calling itself could come in handy:
function replaceArrayKeyValue(array &$arr, $whereKey, $whereValue, $replacement) {
$matched = false;
$keys = array_keys($arr);
for ($i = 0; $i < count($keys); $i++)
{
$key = $keys[$i];
if (is_string($arr[$key])) {
if ($key === $whereKey && $arr[$key] === $whereValue) {
if (is_array($replacement)) {
$arr = array_replace_recursive($arr, $replacement);
} else {
$arr[$key] = $replacement;
}
$matched = $key;
break;
}
} else if (is_array($arr[$key])) {
$m = replaceArrayKeyValue($arr[$key], $whereKey, $whereValue, $replacement);
if ($m !== false) {
$matched = $key.'.'.$m;
break;
}
}
unset($key);
}
unset($keys);
return $matched;
}
With the above function, you pass through the source array ($arr), the key you're looking for ($whereKey), the value that it should match ($whereValue) and the replacement value ($replacement).
If $replacement is an array, I've got a array_replace_recursive in place to perform a recursive replacement, allowing you to pass in the changes you'd like to make to the array. For example, in your case:
$data = unserialize(...);
$matchedKey = replaceArrayKeyValue($data, 'ab-variation-letter', 'C', [
'ab-variation-title' => 'My New Title'
]);
$serialized = serialize($data);
You could replace this with array_recursive if you're not wanting the changes to occur further down any nested child arrays.
When using this function, the $data array is modified directly. The result of the function is a joint string of the key path to that value, in this case:
echo $matchedKey; // Result: 1.ab-variation-letter
If you echo print_r($data, true), you get the intended result:
Array (
[0] => Array( ... )
[1] => Array
(
[ab-variation-letter] => C
[ab-variation-title] => My New Title
[ab-variation-wysiwyg-editor-] => ccccccccccccccccc
[ab-variation-conversion-count] =>
[ab-variation-views] =>
[ab-variation-start-date] =>
[ab-variation-end-date] =>
[ab-variation-winner] =>
)
[2] => Array( ... )
[3] => Array( ... )
)
I got it working after some playing around with this code below. Open to other versions as well thanks
$serialized_meta_data_string = 'a:4:{i:0;a:8:{s:19:"ab-variation-letter";s:1:"B";s:18:"ab-variation-title";s:6:"bbbbbb";s:28:"ab-variation-wysiwyg-editor-";s:12:"bbbbbbbbbbbb";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:1;a:8:{s:19:"ab-variation-letter";s:1:"C";s:18:"ab-variation-title";s:5:"ccccc";s:28:"ab-variation-wysiwyg-editor-";s:17:"ccccccccccccccccc";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:2;a:8:{s:19:"ab-variation-letter";s:1:"D";s:18:"ab-variation-title";s:8:"dddddddd";s:28:"ab-variation-wysiwyg-editor-";s:1:"d";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}i:3;a:8:{s:19:"ab-variation-letter";s:1:"E";s:18:"ab-variation-title";s:8:"eeeeeeee";s:28:"ab-variation-wysiwyg-editor-";s:30:"eeeeeee eeeeeeeeeeeee eeeeeeee";s:29:"ab-variation-conversion-count";s:0:"";s:18:"ab-variation-views";s:0:"";s:23:"ab-variation-start-date";s:0:"";s:21:"ab-variation-end-date";s:0:"";s:19:"ab-variation-winner";s:0:"";}}';
$update_on_key = 'ab-variation-title';
$ab_version = 'C';
$new_value = 'new variation title on variation C';
$new_data = updateMetaArrayData($serialized_meta_data_string, $update_on_key, $ab_version, $new_value);
echo '<pre>';
echo $new_data;
function updateMetaArrayData($serialized_meta_data_string, $update_on_key, $ab_version, $new_value){
$new_meta_data_arrays = array();
//un-serialize meta data string
$meta_data_arrays = unserialize($serialized_meta_data_string);
foreach($meta_data_arrays as $key => $value){
$new_meta_data_arrays[$key] = $value;
if(isset($value['ab-variation-letter']) && $value['ab-variation-letter'] == $ab_version){
$new_meta_data_arrays[$key][$update_on_key] = $new_value;
}
}
echo '<pre>';
print_r($new_meta_data_arrays);
$new_serialized_meta = serialize($new_meta_data_arrays);
return $new_serialized_meta;
}

Build multidimensional array from an array in PHP

I would like to build a multidimensional array from an array. For example I would like
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
to become
$test =
array (
'Tree' => array (
'Trunk' => array (
'Branch' => array (
'Limb' => array (
'Apple' => array (
'Seed' => array ()
)
)
)
)
)
);
or more simply
$result[Tree][Trunk][Branch][Limb][Apple][Seed] = null;
I'm trying to do this with a recursive function but i'm hitting memory limit so I'm clearly doing it wrong.
<?php
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
print_r($test);
print "results of function";
print_r(buildArray($test));
function buildArray (&$array, &$build = null)
{
if (count($array) > 0)
{
//create an array, pass the array to itself removing the first value
$temp = array_values($array);
unset ($temp[0]);
$build[$array[0]] = $temp;
buildArray($build,$temp);
return $build;
}
return $build;
}
Here's an approach with foreach and without recursion, which works:
function buildArray($array)
{
$new = array();
$current = &$new;
foreach($array as $key => $value)
{
$current[$value] = array();
$current = &$current[$value];
}
return $new;
}
[ Demo ]
Now your function... first, using $build[$array[0]] without defining it as an array first produces an E_NOTICE.
Second, your function is going into infinite recursion because you are not actually modifying $array ($temp isn't the same), so count($array) > 0 will be true for all of eternity.
And even if you were modifying $array, you couldn't use $array[0] anymore, because you unset that, and the indices don't just slide up. You would need array_shift for that.
After that, you pass $build and $temp to your function, which results in further because you now you assign $build to $temp, therefore creating another loop in your already-infinitely-recurring loop.
I was trying to fix all of the above in your code, but eventually realized that my code was now pretty much exactly the one from Pevara's answer, just with different variable names, so... that's that.
This function works recursively and does the trick:
function buildArray($from, $to = []) {
if (empty($from)) { return null; }
$to[array_shift($from)] = buildArray($from, $to);
return $to;
}
In your code I would expect you see an error. You are talking to $build in your first iteration as if it where an array, while you have defaulted it to null.
It seems to be easy
$res = array();
$i = count($test);
while ($i)
$res = array($test[--$i] => $res);
var_export($res);
return
array ( 'Tree' => array ( 'Trunk' => array ( 'Branch' => array ( 'Limb' => array ( 'Apple' => array ( 'Seed' => array ( ), ), ), ), ), ), )
Using a pointer, keep re-pointing it deeper. Your two output examples gave array() and null for the deepest value; this gives array() but if you want null, replace $p[$value] = array(); with $p[$value] = $test ? array() : null;
$test = array(
'Tree',
'Trunk',
'Branch',
'Limb',
'Apple',
'Seed'
);
$output = array();
$p = &$output;
while ($test) {
$value = array_shift($test);
$p[$value] = array();
$p = &$p[$value];
}
print_r($output);

what should i do to get array like this in php?

I have one array as below :
Array
(
[Sep] => Array
(
[Support Help Desk] => 24.67
[Development] => 7.74
[Consulting Services] => 4.04
)
[Oct] => Array
(
[Support Help Desk] => 14.38
[Business Activity] => 1.92
[Maintenance Tasks] => 1.00
[Development] => 2.11
)
)
and i want array like this :
Array
(
[Support Help Desk] => 24.67,14.38
[Development] => 7.74,2.11
[Consulting Services] => 4.04,0
[Business Activity] => 0,1.92
[Maintenance Tasks] => 0,1.00
)
I am using php with zend framework.
But i don't know what method should i use to get array like this ?
can anyone please guide me ?
-
Thanks in advance.
Third time lucky! I missed out on some subtleties in the question originally. Try the following code - it's a bit loopy but it should work for you.
I am assuming that your original array is called $data.
// first we need to 'normalise' or fill in the blanks in the contents of the sub array
// get a unique list of all the keys shared - doing it manually here
$keys = ['Support Help Desk', 'Business Activity', 'Maintenance Tasks', 'Development', 'Consulting Services'];
// create a default array with $keys, assigning 0 as the value of each
$default = array_fill_keys($keys, 0);
// next fill in the blanks...
// get the diff (missing keys) between the current element and the default array
// merge the missing key/value pairs
array_walk($data, function(&$month, $key, $default) {
$diff = array_diff_key($default, $month);
$month = array_merge($diff, $month);
}, $default);
// now the array is normalised
// flatten the array... where there are duplicate values for a key, and
// there will be in all cases now including default values
// a sub array is created
$merged = call_user_func_array('array_merge_recursive', $data);
// finally loop over the merged array
// and implode each array of values into a comma separated list
foreach ($merged as &$element) {
if (is_array($element)) {
$element = implode(', ', $element);
}
}
// done :)
var_dump($merged);
Yields:
array (size=5)
'Business Activity' => string '0, 1.92' (length=7)
'Maintenance Tasks' => string '0, 1' (length=4)
'Support Help Desk' => string '24.67, 14.38' (length=12)
'Development' => string '7.74, 2.11' (length=10)
'Consulting Services' => &string '4.04, 0' (length=7)
Hope this helps :)
EDIT
Live example at eval.in
Let's say your array is stored in $main_arr and result array is $result_arr.
$result_arr = array();
foreach ($main_arr as $month) {
foreach ($month as $key => $val) {
if (!isset($result_arr[$key])) {
$result_arr[$key] = array($val);
} else {
array_push($result_arr[$key], $val);
}
}
}
foreach ($result_arr as $key => $val) {
$result_arr[$key] = implode(', ', $val);
}
print_r($result_arr); //Final output.

Stripping out numerical array keys from var_export

I want to do var_export() and strip out all numerical array keys on an array. My array outputs like so:
array (
2 =>
array (
1 =>
array (
'infor' => 'Radiation therapy & chemo subhead',
'PPOWithNotif' => '',
'PPOWithOutNotif' => 'Radiation therapy & chemo PPO amount',
'NonPPO' => 'Radiation therapy & chemo Non PPO amount',
),
),
3 =>
array (
1 =>
array (
'infor' => 'Allergy testing & treatment subhead',
'PPOWithNotif' => '',
'PPOWithOutNotif' => 'Allergy testing & treatment PPO amount',
'NonPPO' => 'Allergy testing & treatment Non PPO amount',
),
)
)
By doing this I can shuffle the array values however needed without having to worry about numerical array values.
I've tried using echo preg_replace("/[0-9]+ \=\>/i", '', var_export($data)); but it doesn't do anything. Any suggestions? Is there something I'm not doing with my regex? Is there a better solution for this altogether?
You have to set the second parameter of var_export to true, or else there is no return value given to your preg_replace call.
Reference: https://php.net/manual/function.var-export.php
return
If used and set to TRUE, var_export() will return the variable
representation instead of outputting it.
Update: Looking back on this question, I have a hunch, a simple array_values($input) would have been enough.
May not be the answer you are looking for, but if you have a one level array, you can use the function below. It may not be beautiful, but it worked well for me.
function arrayToText($array, $name = 'new_array') {
$out = '';
foreach($array as $item) {
$export = var_export($item, true);
$export = str_replace("array (\n", '', $export);
$export = substr($export, 0, -1);
$out .= "[\n";
$out .= $export;
$out .= "],\n";
}
return '$' . $name . ' = ' . "[\n" . substr($out, 0, -2) . "\n];";
}
echo arrayToText($array);
This package does the tricks
https://github.com/brick/varexporter
use Brick\VarExporter\VarExporter;
echo VarExporter::export([1, 2, ['foo' => 'bar', 'baz' => []]]);
Output:
[
1,
2,
[
'foo' => 'bar',
'baz' => []
]
]
Why not just use array_rand:
$keys = array_rand($array, 1);
var_dump($array[$keys[0]]); // should print the random item
PHP also has a function, shuffle, which will shuffle the array for you, then using a foreach loop or the next / each methods you can pull it out in the random order.

Categories