Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ":" in PHP? [closed]

Tags:

syntax

php

What does the symbol : mean in PHP?

like image 417
good_evening Avatar asked May 25 '10 20:05

good_evening


People also ask

What are PHP closures?

Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk() . By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.

What is closure in PHP and why does it use use identifier?

The closure is a function assigned to a variable, so you can pass it around. A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure.

What is closure function in laravel?

Closures are anonymous functions that don't belong to any class or object. Closures don't have specified names and can also access variables outside of scope without using any global variables.

What are anonymous functions in PHP?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.


3 Answers

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

like image 141
dalton Avatar answered Oct 12 '22 12:10

dalton


You also encounter : if you use the alternative syntax for control structures:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

Or as already mentioned the ternary operator:

$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

(Examples taken from the documentation)


Edit: Somehow I didn't see that the alternative syntax was already mentioned, must be too tired ;) Anyway, I will leave it as it is, as I think an actual example and a link to the documentation is more helpful than just plain text.

like image 41
Felix Kling Avatar answered Oct 12 '22 12:10

Felix Kling


I'm guessing you're seeing this syntax:

print ($item ? $item : '');

This is a short form of if/else. The ? is the if, and the : is the else.

like image 9
ceejayoz Avatar answered Oct 12 '22 11:10

ceejayoz