Ok so, I am building something for my employer for them to input products, they have very specific requirements. I have a form with dynamically generated fields like so... (obvi
According to the PHP documentation of key():
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
The documentation (and example) shows that you need to provide the actual array as parameter, where you are using the value.
So use something like this:
$yourArray = $_POST['attribute'];
foreach ($yourArray as $attributes){
echo key($yourArray).' '.$attributes.'<br>';
}
Even though you notice that are aware that you have a 'somewhat unorthodox method of coding in comparison to some', it would be much better to use the foreach
-loop in this way:
foreach ($_POST['attribute'] as $attributeKey => $attributes){
echo $attributeKey.' '.$attributes.'<br>';
}
as the key()
method seems a bit 'dodgy' to me (being dependent on internal pointers).
Check out the foreach documentation for more information on this use.
Ok so, I have fixed it, with the help of you guys and the realization that i had been a little stupid and only edited the static part of the form to incorporate the dynamic key and not the ajax generated part which overwrites it.
foreach ($_POST['attribute'] as $key => $attributes){
echo $key.'+'.$attributes.'<br>';
}
Works perfectly. thanks for the tips guys.
<input type="text" name="attribute[20]"> inputted value = height
<input type="text" name="attribute[27]"> inputted value = width
foreach ($_POST['attribute'] as $attributes){
echo key($attributes).' '.$attributes.'<br>';
}
Note here that you are looping over the attribute array in post. $attributes is the value for each field (and is therefore not an array.
Instead of using key()
try:
foreach ($_POST['attribute'] as $attributeKey => $attributes){
echo $attributeKey.' '.$attributes.'<br>';
}