Stripping out numerical array keys from var_export - php

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.

Related

PHP Nested JSON encoding joining arrays [duplicate]

Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.
I wonder why the simplest method hasn't been posted yet:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Exactly what Pekka said...
Alternatively, you can probably use array_merge like this if you wanted:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings
$settings=getGlobalSettings();
// Apply User Theme Choice
$theme_choice = $settings['theme'];
.. etc etc etc ....
function getGlobalSettings(){
$dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
$MySQL = "SELECT * FROM systemSettings";
$result = mysqli_query($dbc, $MySQL);
while($row = mysqli_fetch_array($result))
{
$settings[$row['item']] = $row['value']; // NO NEED FOR PUSH
}
mysqli_close($dbc);
return $settings;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
This is the solution that may useful for u
Class Form {
# Declare the input as property
private $Input = [];
# Then push the array to it
public function addTextField($class,$id){
$this->Input ['type'][] = 'text';
$this->Input ['class'][] = $class;
$this->Input ['id'][] = $id;
}
}
$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
When you dump it. The result like this
array (size=3)
'type' =>
array (size=3)
0 => string 'text' (length=4)
1 => string 'text' (length=4)
2 => string 'text' (length=4)
'class' =>
array (size=3)
0 => string 'myclass1' (length=8)
1 => string 'myclass2' (length=8)
2 => string 'myclass3' (length=8)
'id' =>
array (size=3)
0 => string 'myid1' (length=5)
1 => string 'myid2' (length=5)
2 => string 'myid3' (length=5)
A bit late but if you don't mind a nested array you could take this approach:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
To clarify,
if you output json_encode($main_array) that will look like [{"Key":"10"}]
A bit weird, but this worked for me
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
// prints array['key1'=>"value1", 'key2'=>"value2"]
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
2023
A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine.
creates the the key with its value in the array
hi i had same problem i find this solution you should use two arrays then combine them both
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
reference : w3schools
For add to first position with key and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
array_push($GET, $GET['one']=1);
It works for me.
I usually do this:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);

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

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

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;
}

How to get value from nested array using string

I have an array like this:
$temp = array( '123' => array( '456' => array( '789' => '0' ) ),
'abc' => array( 'def' => array( 'ghi' => 'jkl' ) )
);
I have a string like this:
$address = '123_456_789';
Can I get value of $temp['123']['456']['789'] using above array $temp and string $address?
Is there any way to achieve this and is it good practice to use it?
This is a simple function that accepts an array and a string address where the keys are separated by any defined delimiter. With this approach, we can use a for-loop to iterate to the desired depth of the array, as shown below.
<?php
function delimitArray($array, $address, $delimiter="_") {
$address = explode($delimiter, $address);
$num_args = count($address);
$val = $array;
for ( $i = 0; $i < $num_args; $i++ ) {
// every iteration brings us closer to the truth
$val = $val[$address[$i]];
}
return $val;
}
$temp = array("123"=>array("456"=>array("789"=>"hello world")));
$address = "123_456_789";
echo delimitArray($temp,$address,"_");
?>
Hello if string $address = '123_456_789'; is your case then you can use explode function to split the string by using some delimeter and you can output your value
<?php
$temp = array('123' => array('456' => array('789' => '0')),
'abc' => array('def' => array('ghi' => 'jkl')),
);
$address = '123_456_789';
$addr = explode("_", $address);
echo $temp[$addr[0]][$addr[1]][$addr[2]];
Using this array library you can easily get element value by either converting your string to array of keys using explode:
Arr::get($temp, explode('_', $address))
or replacing _ with . to take advantage of dot notation access
Arr::get($temp, str_replace('_', '.', $address))
Another benefit of using this method is that you can set default fallback value to return if element with given keys does not exists in array.

How to push both value and key into PHP array

Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.
I wonder why the simplest method hasn't been posted yet:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Exactly what Pekka said...
Alternatively, you can probably use array_merge like this if you wanted:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings
$settings=getGlobalSettings();
// Apply User Theme Choice
$theme_choice = $settings['theme'];
.. etc etc etc ....
function getGlobalSettings(){
$dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
$MySQL = "SELECT * FROM systemSettings";
$result = mysqli_query($dbc, $MySQL);
while($row = mysqli_fetch_array($result))
{
$settings[$row['item']] = $row['value']; // NO NEED FOR PUSH
}
mysqli_close($dbc);
return $settings;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
This is the solution that may useful for u
Class Form {
# Declare the input as property
private $Input = [];
# Then push the array to it
public function addTextField($class,$id){
$this->Input ['type'][] = 'text';
$this->Input ['class'][] = $class;
$this->Input ['id'][] = $id;
}
}
$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
When you dump it. The result like this
array (size=3)
'type' =>
array (size=3)
0 => string 'text' (length=4)
1 => string 'text' (length=4)
2 => string 'text' (length=4)
'class' =>
array (size=3)
0 => string 'myclass1' (length=8)
1 => string 'myclass2' (length=8)
2 => string 'myclass3' (length=8)
'id' =>
array (size=3)
0 => string 'myid1' (length=5)
1 => string 'myid2' (length=5)
2 => string 'myid3' (length=5)
A bit late but if you don't mind a nested array you could take this approach:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
To clarify,
if you output json_encode($main_array) that will look like [{"Key":"10"}]
A bit weird, but this worked for me
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
// prints array['key1'=>"value1", 'key2'=>"value2"]
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
2023
A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine.
creates the the key with its value in the array
hi i had same problem i find this solution you should use two arrays then combine them both
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
reference : w3schools
For add to first position with key and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
array_push($GET, $GET['one']=1);
It works for me.
I usually do this:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);

Categories