PHP - associative array: check the amount of elements within a value (which has an array) of a key

Asked

Viewed 208 times

-6

I have an array like this:

$array = array(
    user => "user1",
    name => "name1",
    books => "book1", "book2"
);

I want to go in Books and check the value that elements have inside it, in case it would be 2 (book1 and Book2). I have tried Count(array['Books']); and array['Books']. length but none of these seem to work. I would like to do that check on an if.

I appreciate any contribution.

  • Dear Sabrina I don’t understand, why did you choose the other answer as correct? She doesn’t show anything like "tell," I won’t interfere with her judgment, but I’d simply like to know where this is the motivation for this and whether it really solved her problem.

2 answers

6


This is not an array within another:

 books => "book1", "book2"

For it to be an array it would have to be like this (ps: put quotes on keys as well):

$array = array(
    "user" => "user1",
    "name" => "name1",
    "books" => array( "book1", "book2" )
);

Or in php5.4+:

$array = [
    "user" => "user1",
    "name" => "name1",
    "books" => [ "book1", "book2" ]
];

The other way you did:

$array = array(
    user => "user1",
    name => "name1",
    books => "book1", "book2"
);

It would be the same as:

$array = array(
    "user" => "user1",
    "name" => "name1",
    "books" => "book1",
    0 => "book2"
);

Allies array['books'].length does not work in PHP, that is probably doesn’t work inside PHP.

See the online example working: https://ideone.com/0vnE3R

The verification in a if would be:

if (count($array['books']) == 2) {
    echo 'Contém 2 elementos';
}

Or:

if (count($array['books']) > 1) {
    echo 'Contém 2 ou mais elementos';
}
  • That’s right, I’ll update the question.

  • Cara @Sabrinab. solved the problem? Tested Count this way?

  • yes, it worked, thank you.

-3

Sabrina, you can use a command called foreach

Your foreach would look like this

foreach ($array as $key => $value)
{
    foreach ($value as $keys => $valor)
    {
        //aqui você pega seu valor
    }
}

Browser other questions tagged

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