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'
);
I have an GLOBAL array that keeps all the configurations, it looks like this:
$_SOME_ARRAY = array(
'some_setting' => array(
'some_value' => '1',
'other' => 'value'
),
'something_else' => 1,
);
How can I delete keys from this array, using some function like:
deleteFromArray('some_setting/other')
I have tried different things, but can't seem to find a way, to delete it without manually calling unset($_SOME_ARRAY['some_setting']['other'])
EDIT
I have tried working on with it. The only solution I see so far, is by "rebuilding" the original array, by looping through each value and verify. The progress:
public static function delete($path) {
global $_EDU_SETUP;
$exploded_path = explode('/', $path);
$newConfig = array();
$delete = false;
foreach($exploded_path as $bit) {
if(!$delete) {
$loop = $_EDU_SETUP;
} else {
$loop = $delete;
}
foreach($loop as $key => $value) {
if($key == $bit) {
echo 'found first: ' . $key . '<br />'; // debugging
if(!$delete) {
$delete = $_EDU_SETUP[$key];
} else {
$delete = $delete[$key];
}
} else {
$newConfig[$key] = $value;
}
}
}
$_EDU_SETUP = $newConfig;
}
The array could look like this:
$array = array(
'a' => array(
'a',
'b',
'c'
),
'b' => array(
'a',
'b',
'c' => array(
'a',
'b',
'c' => array(
'a'
),
),
)
);
And to delete $array['b']['c'] you would write Config::delete('b/c'); - BUT: It deletes whole B. It is only supposed to delete C.
Any ideas?
This what you can do, assuming the array has 2 levels of data.
$_SOME_ARRAY = array(
'some_setting' => array(
'some_value' => '1',
'other' => 'value'
),
'something_else' => 1,
);
function deleteFromArray($param){
global $_SOME_ARRAY ;
$param_values = explode("/",$param);
if(count($param_values) == 2 ){
unset($_SOME_ARRAY[$param_values[0]][$param_values[1]]);
}else{
unset($_SOME_ARRAY[$param_values[0]]);
}
}
deleteFromArray('some_setting/other');
print_r($_SOME_ARRAY);
You can modify the function to add more strict rules by checking if the key exists before doing unset using the function array_key_exists()
how do you like this ?
$_SESSION = $_SOME_ARRAY; // Btw it should be session from beginning...
function deleteFromArray($string)
{
$array = explode("/",$sting);
foreach($array as $arrA)
{
foreach($array as $arrB)
{
unset($_SESSION[$arrA][$arrB]);
}
}
}
now you could delete more than one entry like
deleteFromArray('some_setting/some_value/a_other_value')
but take care of using dim1array names in dim2array...
of corse you could add more foreach or make a recursiv function out of it to get deep in the array
do you want to delete particular array using a unique index(like a primary id)?, i would use a for loop to look for that particular index then delete that array...E.g delete array where the index = 1 , pls check above
foreach ($_SOME_ARRAY as $a => $key)//get all child arrays of '$_SOME_ARRAY '
{
foreach($Key as $b => $key2)//get values of the child arrays
{
if($Key[0] == 1)// if the index at[0] equals 1
{
unset($arr[$a][$b]); //delete that array
}
}
}
I'm trying to remove an object from an array of objects by its' index. Here's what I've got so far, but i'm stumped.
$index = 2;
$objectarray = array(
0=>array('label'=>'foo', 'value'=>'n23'),
1=>array('label'=>'bar', 'value'=>'2n13'),
2=>array('label'=>'foobar', 'value'=>'n2314'),
3=>array('label'=>'barfoo', 'value'=>'03n23')
);
//I've tried the following but it removes the entire array.
foreach ($objectarray as $key => $object) {
if ($key == $index) {
array_splice($object, $key, 1);
//unset($object[$key]); also removes entire array.
}
}
Any help would be appreciated.
Updated Solution
array_splice($objectarray, $index, 1); //array_splice accepts 3 parameters
//(array, start, length) removes the given array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable
array_splice($objectarray, $index, 1);
//array_splice accepts 3 parameters (array, start, length) and removes the given
//array and then normalizes the index
//OR
unset($objectarray[$index]); //removes the array at given index
$reindex = array_values($objectarray); //normalize index
$objectarray = $reindex; //update variable
You have to use the function unset on your array.
So its like that:
<?php
$index = 2;
$objectarray = array(
0 => array('label' => 'foo', 'value' => 'n23'),
1 => array('label' => 'bar', 'value' => '2n13'),
2 => array('label' => 'foobar', 'value' => 'n2314'),
3 => array('label' => 'barfoo', 'value' => '03n23')
);
var_dump($objectarray);
foreach ($objectarray as $key => $object) {
if ($key == $index) {
unset($objectarray[$index]);
}
}
var_dump($objectarray);
?>
Remember, your array will have odd indexes after that and you must (if you want) reindex it.
$foo2 = array_values($objectarray);
in that case you won't need that foreach just unset directly
unset($objectarray[$index]);
This is a question more of style than function. At the moment I use the following code to produce an array of values that have gone through various regex's in a function.
However this means having to reference the final array, which when adding lots of values to an SQL query can start to look quite messy compared to straight variables.
I could extract the array to variables after the function is called but am wondering if there is some way to do this from within the function and not run into problems with scope or should I actually avoid using straight variables and stick with the array?
<?php
function formData($form_vars)
{
$regex_array = array(
'alpha_num' => "/[^a-zA-Z0-9[:space:][:blank:]]/",
'basic' => "/[^a-zA-Z0-9[:space:][:blank:],.\\'()&-]/"
);
foreach ($form_vars as $key => $var) {
$regex = $regex_array[$var];
$val = preg_replace($regex, '', $_REQUEST[$key]);
$vars[$key] = $val;
}
return $vars;
}
$vars = array(
'address_one' => "basic",
'address_two' => "basic",
'address_three' => "basic",
'postal' => "alpha_num"
);
$vars = formData($vars);
echo $vars['address_one'];
?>
To be point on your question and not diverge on other things I'd like to comment on:
$regex_array (which I'd call $softTypeFilters) and $vars (which I'd call $fieldSoftTypes) can be expternalized into a configuration file right now. So I'd stick with this and not use your other suggestion. You might loose this functionality (configurability) which is very powerful. And the code is still easy to read.
You don't need to extract $vars and can use it to build your query easier (with a function build_query($var) for example, with an other loop)
EDIT detailled answer: I think about something like this:
<?php
function formData($vars, $alias)
{
foreach($_POST as $k => $v)
{
// skip unknown fields
if (!isset($vars[$k]))
continue;
// deal with input names != field name
$field_name = isset($form_alias[$k])?$form_alias[$k]:$k;
$vars[$key] = preg_replace($regex, '', $_REQUEST[$key]);
if (function_exists('preprocess_'.$key))
$vars[$key] = call_user_func('preprocess_'.$key, $vars[$key]);
}
return $vars;
}
function buildQuery($vars)
{
$sql = '';
// use a query builder, PDO prepared statements or anything
foreach($vars as $field => $value)
{
// ...
}
return $sql;
}
$vars = array(
'address_one' => "basic",
'address_two' => "basic",
'address_three' => "basic",
'postal' => "alpha_num",
);
$form_alias = array(
'address1' => "address_one",
'address2' => "address_two",
'address3' => "address_three",
);
$vars = formData($vars, $form_alias);
$query = buildQuery($vars);
I am thinking of a good practice to read the client submitted POST data.
For example if I have a post variable that should have the following structure:
array(
[0] => array(
['test'] => array(1, 2, 3),
['test2'] => "string"
),
[1] => array(
['test'] => array(),
['test2'] => "string2"
),
)
Where the indices 'test' and 'test2' should always be present but their values may be empty (array() and "");
The functions that handle the POST data are expecting the correct format, so I have to make sure that the data has not been manipulated.
I could do the following:
$result = array();
if(isset($_POST['myVar']) && is_array($_POST['myVar'])) {
foreach($_POST['myVar'] as $array) {
$new = array('test' => array(), 'test2' = "");
if(isset($array['test']) && is_array($array['test'])) {
foreach($array['test'] as $expectedInt) {
$new['test'][] = (int)$expectedInt;
}
}
if(isset($array['test2']) && is_string($array['test2']))
$new['test2'] = $array['test2'];
}
$result[] = $new;
}
I think you get the idea what I mean. I wonder if there is a better practice of reading the POST data into the expected format.
I usually do this to assure I have default indices:
$par = $_POST;
$par += [
'key' => 'default',
'other' => 'default',
]
If $par doesn't contain those keys, they are set.
In your case, your could do this:
$ready = [];
foreach($_POST as $k => $v){
$v += [
'test' => [],
'test2' => "string2",
];
// Validate if needed
$v['test'] = (array)$v['test'];
$v['test2'] = (string)$v['test2'];
$ready[$k] = $v;
}
Later you can be sure, that $ready will contain values with test and test2 keys.
This is very useful in functions, where you replace a lot of arguments with one parameter array, and then later set default values,