chris.cavage chris.cavage - 1 year ago 83
PHP Question

How to get integer value from array:php

When I do a print_r on my $_POST, I have an array that may look like this:

[action] => remove
[data] => Array
[row_1] => Array
[DT_RowId] => row_1
[name] => Unit 1
[item_price] => 150.00
[active] => Y
[taxable] => Y
[company_id] => 1



The row_1 value can be anything formatted like row_?

I want that number as a string, whatever the number is. That key and the DT_RowID value will always be the same if that helps.

Right now I am doing this, but it seems like a bad way of doing it:

//the POST is a multidimensinal array... the key inside the 'data' array has the id in it, like this: row_2. I'm getting the key value here and then removing the letters to get only the id nummber.
foreach ($_POST['data'] AS $key => $value) {
$id_from_row_value = $key;
//get only number from key = still returning an array
preg_match_all('!\d+!', $id_from_row_value, $just_id);
//found I had to use [0][0] since it's still a multidimensional array to get the id value
$id = $just_id[0][0];

It works, but I'm guessing there's a faster way of getting that number from the $_POST array.

Answer Source
$array = [
    'data' => [
        'row_1' => [],
        'row_2' => [],

$nums = [];
foreach ($array['data'] as $key => $val) {
    $nums[] = preg_replace('@[^\d]@', '', $key);



array (
  0 => '1',
  1 => '2',
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download