What is a scalar variable?

Asked

Viewed 2,954 times

11

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

  • What is a scalar variable?
  • How a scalar variable works?
  • What is the difference between a scalar variable and a nonscalar?
  • What types of variables are scalars?

2 answers

13


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

In linear algebra, we say that a value is scalar to denote a number or simple value, not an algebraic structure. To talk about the algebraic structures themselves would be kind of to deviate from the subject, so to the curious I’ll just leave a link to the corresponding wiki from Algebraic structure.

In programming, a variable is to scale if it is a number, a string or another type of "primitive" sayings in various languages - which is distinct from a structure with more logic and set of implicit operations as an instance of a class or a array. And yes, I know that strings are deep down arrays characters, but receive special treatment in almost every language.

9

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

Nonscalar types are composed or need something else to be manipulated as objects, arrays and Resources.

An example of error (notice in case) common 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'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.