Error Undefined offset in PHP

2

I need to separate the elements of an array according to their type and print them in a list.

<?php

$d[0] = 13;
$d[1] = 133;
$d[2] = 45;
$d[3] = "Hice 89 lagartijas";
$d[4] = 778;
$d[5] = 67;
$d[6] = "Que onda";
$d[7] = 456;
$d[8] = 34;
$d[9] = 645;

for($i=0; $i<=9; $i++){
    switch($d){
        case is_numeric($d[$i]):
            $s[$i] = $d[$i];
            break;
        case is_string($d[$i]):
            $k[$i] = $d[$i];
            break;
    }
}
echo "Numeros <BR>";

for($i = 0; $i<=9; $i++){
    echo "$s[$i] <br>";
}
echo "Textos <BR>";

for($i = 0; $i<=9; $i++){
    echo "$k[$i] <br>";
}
    
asked by Esteban Vera 19.02.2017 в 08:04
source

1 answer

4

Observing your code in detail, the problem is when evaluating the number of elements that have Arrays of numbers and letters.

<?php

$d[0] = 13;
$d[1] = 133;
$d[2] = 45;
$d[3] = "Hice 89 lagartijas";
$d[4] = 778;
$d[5] = 67;
$d[6] = "Que onda";
$d[7] = 456;
$d[8] = 34;
$d[9] = 645;

$indiceNumeros = 0;
$indiceLetras = 0;
for($i=0; $i<=9; $i++){
    switch($d){
        case is_numeric($d[$i]):            
            $s[$indiceNumeros] = $d[$i];
            $indiceNumeros++;
            break;
        case is_string($d[$i]):
            $k[$indiceLetras] = $d[$i];
            $indiceLetras++;
            break;
    }
}
echo "Numeros <BR>";

for($i = 0; $i<count($s); $i++){
    echo "$s[$i] <br>";
}
echo "Textos <BR>";

for($i = 0; $i<count($k); $i++){
    echo "$k[$i] <br>";
}   
?>
  

Numbers Contains only 8 items and not 9

     

13, 133, 45, 778, 67, 456, 34, 645

     

Texts Contains only 2 items and not 9

     

I did 89 push-ups, what a wave

Recommendation:

Evaluate by the number of elements that a array has with the function count and declare variables for consecutive indexes.

In case you do not need to declare variables to identify the consecutive indexes another way to insert elements to a array is using the function array_push .

For example:

<?php
$pila = array("naranja", "plátano");
array_push($pila, "manzana", "arándano");
print_r($pila);
?>
    
answered by 19.02.2017 / 08:56
source