Asked  7 Months ago    Answers:  5   Viewed   42 times

I wan to convert a string for example 1,2,3,4,5,6 to an array of integers in php? I find functions that only have access to the first character of the string for example 1. How can I conert the whole string to array?

function read_id_txt()
{

        $handle_file = fopen("temporalfile.txt", 'r'); 

        $i=0;

        while ($array_var[$i] = fgets($handle_file, 4096)) { 
            echo "<br>";
            print_r($array_var[i]);
            $i++;
        }

        fclose($handle_file);   

        $temp=explode(" ", $array_var[0]);      

        return $temp;   


}

 Answers

77

Use PHP's explode.

$str = "1,2,3,4,5,6";
$arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );

foreach ($arr AS $index => $value)
    $arr[$index] = (int)$value; 

// casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );

As suggested by Tim Cooper, using array_walk is simpler than the above loop:

array_walk($arr, 'intval');
Wednesday, March 31, 2021
 
Magnanimity
answered 7 Months ago
94

To add to Rikesh's answer:

<?php
$aryMain = array(array('hello','bye'), array('',''),array('','')); 
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);

?>

Sticking his code into another array_filter will get rid of the entire arrays themselves.

Array
(
    [0] => Array
        (
            [0] => hello
            [1] => bye
        )

)

Compared to:

$aryMain = array_map('array_filter', $aryMain);

Array
(
    [0] => Array
        (
            [0] => hello
            [1] => bye
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

)
Wednesday, March 31, 2021
 
drowneath
answered 7 Months ago
10

From the manual (emphasis mine):

The key can either be an integer or a string. The value can be of any type.

Additionally the following key casts will occur:

  • Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
  • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under
      8.
  • [...]

That's not related with the fact that PHP arrays are sparse.

You can verify all this with var_dump().

Wednesday, March 31, 2021
 
daiscog
answered 7 Months ago
69

as in C, strings are arrays in php

then

<?php
$a = "hola";

for($i=0; $i < strlen($a); $i++) {
 echo $a[$i] . "n";

}

$a[2] = "-"; // will print ho-a
?>

what operation do you want to do?

Saturday, August 7, 2021
 
Marko Kevac
answered 3 Months ago
75

The call fails with the same reason the following will also fail:

string foo = string.Format("{0} {1}", 5);

You are specifying two arguments in the format but only specifying one object.

The compiler does not catch it because int[] is passed as an object which is a perfectly valid argument for the function.

Also note that array covariance does not work with value types so you cannot do:

object[] myInts = new int[] {8,9};

However you can get away with:

object[] myInts = new string[] { "8", "9" };
string bar = string.Format("{0} {1}", myInts);

which would work because you would be using the String.Format overload that accepts an object[].

Wednesday, August 11, 2021
 
hakimoun
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :