PHP - associative array: check the amount of elements inside a value (that has an array) of a key [closed]

-6

I have an array like this:

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

I want to go into books and check the value that elements have inside it, in case it would be 2 (book1 and book2). I already tried count (array ['books']); and array ['books']. length but none of these seems to work. I would like to do this check in an if.

Thanks for any input.

    
asked by anonymous 03.09.2018 / 20:47

2 answers

5

This is not an array inside another:

 books => "book1", "book2"

To be an array would have to be like this (ps: put quotation marks around the keys too):

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

Or in php5.4 +:

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

Otherwise 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"
);

Aliais array['books'].length does not work in PHP, ie probably does not work inside PHP.

See the example online working: link

The check 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';
}
    
03.09.2018 / 20:52
-4

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
    }
}
    
03.09.2018 / 20:51