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)."#";
 ?>

Procedimiento almacenado alta clientes

CREATE DEFINER=`root`@`localhost` PROCEDURE `alta_cliente`(in p_country varchar(50),
in p_city varchar(50),
in p_address varchar(50),
in p_first_name varchar(50),
in p_last_name varchar(50),
out p_customer_id int)
BEGIN

declare v_country_id int;
declare v_city_id int;
declare v_address_id int;
declare v_customer_id int;

select country_id into v_country_id from country
where country=p_country;

IF v_country_id is null then
 insert into country(country) values (p_country);
 select last_insert_id() into v_country_id;
END IF;

select city_id into v_city_id from city
where city=p_city and country_id=v_country_id;

IF v_city_id is null then
 insert into city(city,country_id)
 values (p_city,v_country_id);
 select last_insert_id() into v_city_id;
END IF;

select address_id into v_address_id from address
where address=p_address and city_id=v_city_id;

IF v_address_id is null then
 insert into address(address,city_id)
 values (p_address,v_city_id);
 select last_insert_id() into v_address_id;
END IF;

select customer_id into v_customer_id from customer
where first_name=p_first_name and last_name=p_last_name and address_id=v_address_id;

IF v_customer_id is null then
 insert into customer(first_name,last_name,address_id,store_id)
 values (p_first_name,p_last_name, v_address_id,1);
 select last_insert_id() into v_customer_id;
END IF;

select v_customer_id into p_customer_id;

END

call alta_cliente('Spain','Logroño','Laurel, 4','Juan','Pi',@id);
select @id;

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