Current Location: Home> Latest Articles> Common Methods to Convert Array Element Values to Integer Type in PHP

Common Methods to Convert Array Element Values to Integer Type in PHP

gitbox 2025-07-14

Introduction

In PHP, arrays are commonly used and important data structures that can store multiple values of various types. These values can be integers, strings, objects, and more. However, there are cases when you need to convert the element values of an array to integer type. This task can be easily accomplished using some built-in PHP functions.

Using Built-in Functions to Convert Element Values to Integer Type

Using the intval() Function

intval() is a built-in PHP function that converts a given value to an integer. You can iterate over the array and apply this function to each element to convert the values of the array to integers.


$numbers = array(2.3, 4.5, 6.7);
foreach ($numbers as $key => $value) {
  $numbers[$key] = intval($value);
}

In the example above, we convert each element in the $numbers array to an integer, resulting in the array array(2, 4, 6).

Using Type Casting

PHP also supports type casting to convert element values to integers. You can use either (int) or (integer) for the type conversion.


$numbers = array(2.3, 4.5, 6.7);
foreach ($numbers as $key => $value) {
  $numbers[$key] = (int) $value;
}

Using type casting, each element in the $numbers array is converted to an integer, with the final result being array(2, 4, 6).

Considerations

Element Value Types

Before converting array elements, make sure their types are suitable for conversion. For elements that are already integers, the conversion will have no effect. For other types, such as strings, the conversion will change them to integers.

Converted Values

The converted integer values will replace the original element values. If you wish to retain the key-value pairs, consider using an associative array to store and convert the elements.


$numbers = array("a" => 2.3, "b" => 4.5, "c" => 6.7);
foreach ($numbers as $key => $value) {
  $numbers[$key] = (int) $value;
}

In this example, the key-value pairs in the array are preserved, and each element value is successfully converted to an integer.

Conclusion

By using PHP's intval() function or type casting, we can easily convert array element values to integer types. Depending on your use case, you can choose the appropriate method. It's important to ensure that the element values are compatible with the desired conversion to avoid unexpected errors.