$t= creaArray(4, 6); echo array_to_table($t); function creaArray($ancho, $alto) { for ($i = 0; $i < $alto; $i++) { for ($j = 0; $j < $ancho; $j++) { $c[$i][$j] = $j + $i * $ancho; } } return $c; } function cuadrado_magico($ancho){ if ($ancho%2==0) $ancho--; $posy=0; $posx=floor($ancho/2); $cont=1; while ($cont<=$ancho**2){ if (empty($c[$posy][$posx])){ $c[$posy][$posx]=$cont++; $posx=($posx+1)%$ancho; $posy=($posy-1+$ancho)%$ancho; } else{ $posx=($posx-1+$ancho)%$ancho; $posy=($posy+2)%$ancho; } } return $c; } $c= cuadrado_magico(3); echo array_to_table($c); $c= cuadrado_magico(5); echo array_to_table($c);
Arrays multidimensionales en PHP
$b=array(array('A','b'),array('c','d','e','f'),array('g','h','i')); echo "<pre>"; print_r($b); echo "</pre>"; echo $b[1][2]; echo "<br/>"; for ($i=0;$i<count($b);$i++){ for($j=0;$j<count($b[$i]);$j++){ echo "($i,$j) ".$b[$i][$j]." | "; } echo "<br/>"; } foreach($b as $valor){ foreach($valor as $letra){ echo $letra."|"; } echo "<br/>"; } for ($i = 0; $i < 5; $i++) for ($j = 0; $j < 5; $j++) $c[$i][$j] = $j + $i * 5; echo array_to_table($c); function array_to_table($tabla) { $res="<table border=1>"; for ($i = 0; $i < count($tabla); $i++) { $res.="<tr>"; for ($j = 0; $j < count($tabla[$i]); $j++) { $res.="<td>" . $tabla[$i][$j] . "</td>"; } $res.="</tr>"; } $res.="</table>"; return $res; } //Mezcla sin sentido, a lo loco: $tutifruti=array('juan'=>array('a','b','c'),'ana'=>array('c'=>3,'d'=>6,'e'=>8),'rosa'=>array('j','k',array(1,2,3,4))); var_dump($tutifruti);
Arrays asociativos en PHP
$a=array('Juan'=>'Técnico','Ana'=>'Marketing','Rosa'=>'Administración'); $a['Jose']='Ventas'; echo $a['Juan']."<br/>"; foreach($a as $clave=>$valor){ echo $clave." - ".$valor."<br/>"; } echo "<pre>"; print_r($a); var_dump($a); echo "</pre>";
Funciones php
function ajedrez($i, $j) { if (($i + $j) % 2 == 0) { return 'class="par"'; } return ''; } function tablero($tam = 8) { ?> <table border="1"> <?php for ($j = 0; $j < $tam; $j++) { ?> <tr> <?php for ($i = 0; $i < $tam; $i++) { ?> <td <?= ajedrez($i, $j) ?> ></td> <?php } ?> </tr> <?php } ?> </table> <?php } function creaTD($num, $cont) { $res = ""; for ($i = 0; $i < $num; $i++) { $res.="<td>" . ($cont++) . "</td>"; } return $res; } function creaTR($num,$col,$cont){ $res = ""; for ($i = 0; $i < $num; $i++) { $res.="<tr>" . creaTD($col, $cont) . "</tr>"; $cont+=$col; } return $res; }
Funciones de números en PHP
Con is_numeric sabemos si una variable es numérica (aunque sea un string)
foreach ([5, '5', '05', 12.3, '16.7', 'cinco', 0xDECAFBAD, '10e200', '45r'] as $maybeNumber) { $isItNumeric = is_numeric($maybeNumber); $actualType = gettype($maybeNumber); print "Es el $actualType $maybeNumber numerico? "; if (is_numeric($maybeNumber)) { print "Sí"; } else { print "No"; } print " "; }
Redondeos:
$number = round(2.4); // Devuelve 2 $number1 = floor(2.1); // floor(2.1) is the float 2.0 $number2 = floor(2.9); // floor(2.9) is the float 2.0, also $number3 = floor(-2.1); // floor(-2.1) is the float -3.0 $number4 = floor(-2.9); // floor(-2.9) is the float 3.0, also $number1 = ceil(2.1); // ceil(2.1) is the float 3.0 $number2 = ceil(2.9); // ceil(2.9) is the float 3.0, also $number3 = ceil(-2.1); // ceil(-2.1) is the float -2.0 $number4 = ceil(-2.9); // ceil(-2.9) is the float 2.0, also
Siempre podemos poner un segundo parámetro que es la precisión (número de decimales)
Una función poco conocida, range, nos devuelve un rango de números:
print_r(range(1,10,2)); // Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 )
Para obtener números aleatorios tenemos las funciones rand y mt_rand (lo mismo pero mejorada)
int rand ( int $min , int $max ) int mt_rand ( int $min , int $max )
Para usar números grandes, se pueden usar las librerías BCMath o GMP:
$sum = bcadd('1234567812345678', '8765432187654321'); $sum = gmp_add('1234567812345678', '8765432187654321');
Soluciones ejercicios
$long = 6; $cadena = "*"; for ($i = 0; $i < $long; $i++) { echo $cadena . "<br/>"; $cadena.="*"; } echo "<pre>"; for ($i = 1; $i <= $long / 2; $i++) { echo str_repeat(" ", $long / 2 - $i) . str_repeat("*", $i * 2) . str_repeat(" ", $long / 2 - $i) . "<br/>"; } for ($i = $long / 2; $i >= 1; $i--) { echo str_repeat(" ", $long / 2 - $i) . str_repeat("*", $i * 2) . str_repeat(" ", $long / 2 - $i) . "<br/>"; } echo "</pre>"; echo "<pre>"; $i = 1; $inc = 1; while ($i > 0) { echo str_repeat(" ", $long / 2 - $i) . str_repeat("*", $i * 2) . str_repeat(" ", $long / 2 - $i) . "<br/>"; if ($i >= ($long-1) / 2) { $inc = -1; } $i+=$inc; } echo "</pre>"; $lado = 6; $cont=1; ?> <table border="1"> <?php for ($j = 0; $j < $lado; $j++) { ?> <tr> <?php for ($i = 0; $i < $lado; $i++) { ?> <td><?= $cont++ ?></td> <?php } ?> </tr> <?php } ?> </table> <table border="1"> <tr> <?php for ($i=1;$i<=$lado**2;$i++){ echo "<td>".($i)."</td>"; if ($i%$lado==0){ echo "</tr><tr>"; } } ?> </tr> </table>
Ejercicios PHP
Tenemos una variable $tam y queremos una lista (ul/li) con la longitud de $tam.
Ejemplo: $tam=4 nos muestra:
- Elemento 1
- Elemento 2
- Elemento 3
- Elemento 4
Tenemos una variable $long y queremos un árbol de asteriscos de longitud $long
Ejemplo: $long=6 nos muestra:
* ** *** **** ***** ******
Lo mismo con un rombo:
** **** ****** ****** **** **
Tenemos una variable $lado y queremos una tabla cuadrada de ese lado.
Ejemplo: $lado = 4
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 |
Más pasitos en PHP
<?php $a = 3; $b = 3; if ($a > $b * 2) { echo 'a es mucho mayor que b'; } elseif ($a > $b) { echo 'a es mayor que b'; } elseif ($a * 2 < $b) { echo 'a es mucho menor que b'; } elseif ($a < $b) { echo 'a es menor que b'; } else { echo 'iguales'; } echo 'hola que tal'; if ($a) { } ?> <hr/> <?php $a = 1; while ($a ** 3 < 1000) { echo ($a ** 3) . "<br/>"; $a++; } ?> <hr/> <?php for ($i = 1; $i < 100; $i*=2) { echo $i . "<br/>"; } $tabla = array('Ana', 'Juan', 'Rosa'); foreach ($tabla as $nombre) { echo $nombre . "<br/>"; } ?> <hr/> <?php $tabla = 5; //Imprimiendo el HTML echo "<table border=1>"; for ($i = 1; $i <= 10; $i++) { echo "<tr><td>$i</td><td>x</td><td>$tabla</td><td>" . ($i * $tabla) . "</td></tr>"; } echo "</table>"; //Mezclando HTML y PHP. Recordemos que <?= es equivalente a <?php echo ?> <table border=1> <?php for ($i = 1; $i <= 10; $i++) { ?> <tr><td><?= $i ?></td><td>x</td><td><?= $tabla ?></td><td><?= ($i * $tabla) ?></td></tr> <?php } ?> </table>
Primeros pasos en PHP
<?php $a=2; $b=3; echo "suma: \n"; echo $a+$b; //Muestra 5 echo "<br/>concatenar: "; echo $a.$b; //Muestra 23 ?> <hr/> <?php $a=5; $b=4.2; $d=false; $e="7up"; echo $a+$e; echo gettype($a); echo "<br/>"; echo gettype($b); echo "<br/>"; echo gettype($d); echo "<br/>"; echo gettype($e); echo "<br/>"; ?> <hr/> <?php $a=5; $b=true; echo "#".($a==$b)."#"; echo "<br/>"; echo "#".($a===$b)."#"; ?>
Crear funciones
Ejemplos:
CREATE DEFINER=`root`@`localhost` FUNCTION `inventory_in_stock`(p_inventory_id INT) RETURNS tinyint(1) READS SQL DATA BEGIN DECLARE v_rentals INT; DECLARE v_out INT; SELECT COUNT(*) INTO v_rentals FROM rental WHERE inventory_id = p_inventory_id; IF v_rentals = 0 THEN RETURN TRUE; END IF; SELECT COUNT(rental_id) INTO v_out FROM inventory LEFT JOIN rental USING(inventory_id) WHERE inventory.inventory_id = p_inventory_id AND rental.return_date IS NULL; IF v_out > 0 THEN RETURN FALSE; ELSE RETURN TRUE; END IF; END select inventory_in_stock(30) CREATE DEFINER=`root`@`localhost` FUNCTION `clientes_por_pais` (p_country varchar(50)) RETURNS int(11) BEGIN declare total int; SELECT count(customer_id) into total FROM sakila.country left join city using (country_id) left join address using (city_id) left join customer using (address_id) where country=p_country group by country; RETURN total; END select clientes_por_pais('Algeria') CREATE DEFINER=`root`@`localhost` FUNCTION `peliculas_por_actor`(p_actor_id int) RETURNS int(11) BEGIN declare total int; select count(film_id) into total from film join film_actor using (film_id) join actor using(actor_id) where actor.actor_id=p_actor_id; RETURN total; END select peliculas_por_actor(1) CREATE DEFINER=`root`@`localhost` FUNCTION `total_ventas`() RETURNS decimal(10,2) BEGIN declare total decimal(10,2); select sum(amount) into total from payment; RETURN total; END