0

I have an array like this :

 [▼
  0 => array:47 [▼
    "ProductID" => "37883"
    "ProductCode" => "G-49211"
    "ProductName" => "Preludes"
    "StockStatus" => "2"
    "LastModified" => "2014-02-27T09:50:00-08:00"
    "LastModBy" => "1"
    "ProductPopularity" => "110"
    "AutoDropShip" => "N"
  1 => [
    "ProductID" => "37884"
    "ProductCode" => "G-49212"
    "ProductName" => "Preludes "
    "StockStatus" => "2"
    "LastModified" => "2014-02-27T09:50:00-08:00"
    "LastModBy" => "1"
    "ProductPopularity" => "110"
    "AutoDropShip" => "N"
  ]
]

but all values of this array are strings. I want to iterate over this array and cast its values to their original types. if ProductID is integer I want to convert it to integer. Convert dates to real date blabla.

Can this be done ?

3
  • Why do need/want to do this? There is no date type and also which original types anyway? Commented Aug 6, 2016 at 21:29
  • how about this values: "true", "1.44", "null" ? Commented Aug 6, 2016 at 21:31
  • date can be datetime object. Anyway I just want to clear this array. If prices are float or double, I want them to be shown as double or float not string. Commented Aug 6, 2016 at 21:31

1 Answer 1

1

There isnt any real function in php that can parse away array elements based on their data types, but still you can do it using preg_match pattern matching techniques, by recognizing the characters in each element and then type converting them

idea :- use a foreach loop and take each element and apply preg_match to check what kind of data that is and then set a data type for it :)

Sign up to request clarification or add additional context in comments.

2 Comments

that sounds like a great idea for now. What if this array has 1000 items, What about performance ? and of course If I wanted this function I should ignore the performance I guess.
I dont think implementing this will effect the performance, there are rather more performance strains like cryptographic hash generations while login authorizations, Ive once seen how the php's session id works and i was struck such huge computations and yet no performance constrains, your problem isnt much compared to those. yet there may be a better way for your problem..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.