What is a scalar variable?

11

I was reading the PHP documentation and a function is_scalar() - as said by the site itself - when it is used it will inform if a certain variable is scalar. However, I wanted to know more about these scalar variables:

  • What is a scalar variable?
  • How does a scalar variable work?
  • What is the difference between a scalar variable and a non-scalar variable?
  • What types of variables are scalar?
asked by anonymous 18.08.2017 / 20:53

2 answers

13

The simplest answer is that this term, which is used not only with PHP but as with most other languages, comes from linear algebra.

In linear algebra, we say that a value is scalar to denote a simple number or value, not an algebraic structure. Talking about the algebraic structures themselves would kind of divert the subject, so for the curious I'll just leave a link to the corresponding wiki of the Algebraic structure .

In programming, a variable is scalar if it is a number, a string or another type of so-called "primitives" in several languages - which is distinct from a more logical structure and set of implicit operations as an instance of a class or an array . And yes, I know that strings are in the background arrays of characters, but receive special treatment in almost every language.     

18.08.2017 / 21:04
9

A scalar variable is a simple value such as an int , float , string , boolean . This type can be accessed / manipulated without any additional instruction, just call it, other than an array or some other you have to specify the element or key.

Non-scalar types are composed or need something more to be manipulated as objects, arrays and resources.

An example of a common error is trying to print a composite type:

$arr = array('nome' => 'Fulano');
echo $arr; // Notice: Array to string conversion 

//O correto seria especificar qual elemento do array deseja manipular. Por exemplo:
echo $arr['nome'];
    
18.08.2017 / 21:01