Skip to content Skip to sidebar Skip to footer

Php: Get Index Of Element With Tag Name

I'm trying to get the index of an HTML element and pass this to a PHP variable to eventually upload to a database.

You could change your HTML so that the input names include the DIV indexes.

<form><div><textareaname="paragraph[0]"></textarea></div> //index 0
    <div><textareaname="something_else"></textarea></div> index 1
    <div><textareaname="paragraph[2]"></textarea></div> //index 2
    <div><textareaname="paragraph[3]"></textarea></div> //index 3
</form>

Since you're generating the HTML dynamically, the loop that creates it should be able to insert the DIV index into the names of the text areas.

Then your PHP can get the indexes by adding to the foreach.

foreach ($_POST['paragraph'] AS$divindex => $paragraph)

Solution 2:

You could use a base array to hold all your items such as the below HTML:

<div><textareaname="items[][paragraph]"></textarea></div> //index 0
<div><textareaname="items[][something_else]"></textarea></div> index 1
<div><textareaname="items[][paragraph]"></textarea></div> //index 2
<div><textareaname="items[][paragraph]"></textarea></div> //index 3

Then when you access $_POST['items'] you will have them listed with their indexes:

array (size=1)
  'items' => 
    array (size=4)
      0 => 
        array (size=1)
          'paragraph' => string'test' (length=4)
      1 => 
        array (size=1)
          'something_else' => string'test 2' (length=6)
      2 => 
        array (size=1)
          'paragraph' => string'test 3' (length=6)
      3 => 
        array (size=1)
          'paragraph' => string'test 4' (length=6)

You can get all the information held in this array easily using the below loop:

foreach($_POST['items'] as$index => $item) {
  echo"Index is: " . $index;
  echo"Key is: " . key($item);
  echo"Value is: " . $item[key($item)];
}

Which will print:

Index is: 0Keyis: paragraph
Value is: test

Index is: 1Keyis: something_else
Value is: test 2

etc.

If you want to get all values for paragraph in one easy swoop you can use array_column to access these, for example the below:

array_column($_POST['items'], 'paragraph');

Will print:

array (size=3)
  0 => string'test' (length=4)
  1 => string'test 3' (length=6)
  2 => string'test 4' (length=6)

Post a Comment for "Php: Get Index Of Element With Tag Name"