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


Sql views

create or replace view cliente_gaston as
select customer.customer_id first_name, last_name, sum(amount) as total
from customer join payment using(customer_id)
group by first_name, last_name
order by total desc
limit 0,5
update customer set active=5
where customer_id in (select customer_id from cliente_gaston)

Más SQL

Países con tiendas:

select country, count(store_id) as total
from country left join city using (country_id)
left join address using (city_id)
left join store using (address_id)
group by country
having total>0

Cliente que más gasta:

select first_name, last_name, sum(amount) as total
from customer join payment using(customer_id)
group by first_name, last_name
order by total desc
limit 0,1

Ejemplos de CASE e IF:

SELECT *,
case when amount<1 then 'barato'
when amount between 1 and 3 then 'medio'
else 'caro' end precio,
if (amount<3,'barato','caro') precio2
FROM sakila.payment;

Con funciones de agregado:

select first_name, last_name, sum(amount) as total,
if (sum(amount)>100,'gastador','rácano') tipo
from customer join payment using(customer_id)
group by customer_id

Pagos formateados:

SELECT lpad(format(amount,3),10,' ') from payment

Nombre formateado y ordenar por longitud de apellido:

select ucase(first_name), lcase(last_name),
concat(
ucase(substring(first_name,1,1)),
lcase(substring(first_name,2))
) cliente,
length(last_name) longitud
from customer
order by longitud desc