I'm trying to store the users's input via the method get in an array to store it and further process it without overwriting the initial get-value. But I dont know how.. do I have to store them in a database to do that? Or can I just push every input into an array?
I believe the following should work for you... This will take all the $_GETs that you supply and put them in a new array so you can modify them without affecting the original $_GET array.
if(is_array($_GET)){
$newArr = $_GET; // modify $newArr['postFieldName'] instead of $_GET['postFieldName'] to preserve original $_GET but have new array.
}
That solution there will dupe the $_GET array. $_GET is just an internal PHP array of data, as is $_POST. You could also loop through the GETs if you do not need ALL of the GETs in your new array... You would do this by setting up an accepted array of GETs so you only pull the ones you need (this should be done anyways, as randomly accepting GETs from a form can lead to some trouble if you are also using the GETs for database/sql functions or anything permission based).
if(is_array($_GET) && count($_GET) > 0){
$array = array();
$theseOnly = array("postName", "postName2");
foreach($_GET as $key => $value){
if(!isset($array[$key]) && in_array($key, $theseOnly)){ // only add to new array if they are in our $theseOnly array.
$array[$key] = $value;
}
}
print_r($array);
} else {
echo "No $_GET found.";
}
I would just add to what #Nerdi.org said.
Specifically the second part, instead of looping through the array you can use either array_intersect_key or array_diff_key
$theseOnly = array("postName", "postName2");
$get = array_intersect_key( $_GET, array_flip($theseOnly);
//Or
$get = array_diff_key( $_GET, array_flip($theseOnly);
array_intersect_key
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
So this one returns only elements you put in $theseOnly
array_diff_key
Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
So this one returns the opposite or only elements you don't put in $theseOnly
And
array_flip
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
This just takes the array of names with no keys (it has numeric keys by default), and swaps the key and the value, so
$theseOnly = array_flip(array("postName", "postName2"));
//becomes
$theseOnly = array("postName"=>0, "postName2"=>1);
We need the keys this way so they match what's in the $_GET array. We could always write the array that way, but if your lazy like me then you can just flip it.
session_start();
if(!isset($_SESSION['TestArray'])) $_SESSION['TestArray'] = array();
if(is_array($_GET)){
$_SESSION['TestArray'][] = $_GET;
}
print_r($_SESSION['TestArray']);
Thanks everybody for helping! This worked for me!
Related
contains the following i am trying get array_unique value from multidimensional associative array
Here, i am only showing only sample array which is similar to this.
$array = ['games'=>[['vollyball', 'football'], ['vollyball', 'football'], ['rubby', 'chess']]];
Here is tried so for
foreach ($array as $key => &$value) {
$value = array_unique($value);
}
echo "<pre>";
print_r($array);
echo "</pre>";
exit;
Here i am expecting output is,
$array = ['games'=>[['vollyball', 'football'], ['rubby', 'chess']]];
Here the array should be same even after removing duplicate from multidimensional array.
Thanks for your time and suggestions.
you could try the following:
$a=array_values(array_unique(array_merge(...$array['games'])));
This assumes that all your usable values are below $array['games'].
Edit:
Here is another way, using array_walk:
array_walk($array['games'],function($itm){global $res; $res[json_encode($itm)]=$itm;});
echo json_encode(array_values($res));
I don't like the global $res array very much, but this is a way forward, I believe. In the callback function of array_walk() I add all values to an associative array ($res). The keys are JSON representations of their actual values. This way I will overwrite identical values in the associative array $res and will end up with a set of unique values when I apply the array_values() function at the end to turn it back into a non-associative array.
The result is:
[["vollyball","football"],["rubby","chess"]]
Here is a little demo you can check out: http://rextester.com/JEKE60636
2. edit
Using a wrapper function I can now do without the global variable $res and do the operation in-place, i. e. removing duplicate elements directly from the source array:
function unique(&$ag){
array_walk($ag,function($itm,$key) use (&$ag,&$res) {
if (isset($res[json_encode($itm)])) array_splice($ag,$key,1);
else $res[json_encode($itm)]=1.;
});
}
unique($array['games']);
echo json_encode($array)
This will result in
{"games":[["vollyball","football"],["rubby","chess"]]}
see here: http://rextester.com/YZLEK39965
I need to remove a element from an associative array with an string structure.
Example:
$array = array(
"one"=>array("Hello", "world"),
"two"=>"Hi"
)
I want to create a function that removes the elements like this:
function removeElement($p) {
// With the information provided in $p something like this should happen
// unset($array["one"]["hello"])
}
removeElement("one.hello");
Your base array is associative, the inner array (key one) is not, its a indexed array, which you can not access via ["hello"] but rather [0].
You can remove the hello value by using the unset function, but the indexes will stay as they are:
$array = ['Hello', 'World']; // array(0: Hello, 1: World)
unset($array[0]); // Array is now array(1: World)
If you wish to keep unset and keep the array indexes in order, you can fetch the values using the array_values function after unset:
unset($array[0]);
$array = array_values($array); // array(0: World)
Or you could use array_splice.
When it comes to using a string as key for multidimensional array with a dot-separator I'd recommend taking a look at laravels Arr::forget method which does pretty much exactly what you are asking about.
This would be a static solution to your question, in any case, you need to use explode.
function removeElement($p, $array) {
$_p = explode('.', $p);
return unset($array[$_p[0]][$_p[1]]);
}
But bear in mind, this doesn't work if you have more in $p (like: foo.bar.quux)
i am at prototype stage. I have a link in page1.php that sends to page below:
http://localhost/sayfa.php?rd_dil=turkish&rd_sayfa=yazilar&rd_yazar=ali_uysal&rd_baslik=kalem_ucu"
in this page, echo $_GET['rd_dil'] works and displays turkish but echo $_GET[0] displays a Notice : Undefined offset: 0
so I want to work with $_GET in numerical way (numerical index) ? how can I achieve this aim? I read php.net + stack overflow and googled but I couldn't solve my issue.
$_GET is an assoziative array, to loop over it:
foreach($_GET as $key=>$value) {
....
}
In case you want only the values in a numeric array, you could use:
$myData = array_values($_GET);
// here you have a numeric array containing the $_GET values
echo $myData[0];
Since $_GET is an associate array, you can assign the values to a new array:
foreach($_GET as $key=>$val) {
$_GET2[] = $val;
}
Or you can use array_values as suggested by axel.michel:
$_GET2 = array_values($_GET);
echo $_GET2[0];
You can’t do that directly. But there are some workarounds:
$indexed = array_values($_GET);
$first = $indexed[0];
$keys = array_keys($_GET);
$first = $_GET[$keys[0]];
$first = current(array_slice(array('foo'), 0, 1)));
Yes, you can't. That's just how it works.
There is just no such index.
You don't need numerical indexes though, but have to use associative keys.
There are 2 reasons why you shouldn't translate your $_GET into enumerated list:
parameter order is not guaranteed. you have to use field names instead of positions.
it's just useless waste of CPU. Everything you want from your enumerated array, you can get from original $_GET. Use foreach() to iterate it for example.
If you still don't know how to handle $_GET properly - ask this very question, and you will get the proper answer.
I have a bunch of arrays, which are stored in different variables like $required, $reserved, etc...
I would like to allow (inside a function) an array of options to be passed (like $options = array('required', 'reserved')), and that array would then be used to define which arrays to merge together and return at the end of the function.
So, I have this code in part of the function, that should grab all the options and merge the arrays, using variable variables to get the arrays from the strings passed in the options array):
$array = array();
foreach ($options as $key) {
$array_to_merge = ${$key};
array_merge($array, $array_to_merge);
}
return $array;
However, when I return the $array, it shows 0 items. If I print_r($array_to_merge);, I actually get the entire array as I should.
Does array_merge() simply not work with variable variables, or am I missing something here...?
array_merge returns the merged array, you're not assigning that return value to anything and thus it is being lost.
$array = array_merge($array, $array_to_merge);
should fix your problem.
If I read it right you can also simplify your code (replaces the loop) to just:
$array = call_user_func_array("array_merge", compact($options));
compact replaces the variable variable lookup and gets the list of arrays. And in effect there is only one array_merge call necessary.
I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.